2017-10-10 37 views
0

這應該很簡單,但我是matlab新手,所以請原諒。Matlab:如何通過函數傳遞列表,返回答案列表

我在做一個函數函數,它將一個函數y =「一些x的函數」作爲輸入。 y可以是一個函數句柄(假設y = @(x)x^2),或者我可以是一個符號表達式(比如y = x^2)......任何東西都比較容易。

我想通過函數y運行x列表,並返回計算出的y值列表。所以結果應該是[1 4 9 16 25]。我如何在函數函數中做到這一點?

它應該是這個樣子:

function myfunc = func(f) 
    xlist = [1 2 3 4 5]; %IMPORTANT: in this case, xlist's class is "sym" 
    ylist = ... %statement of something like "f(xlist)" goes here* 

回答

0

您可以Ÿ作爲功能手柄,在M檔自稱.....

y = @(x) x.^2 ; 
x = [1 2 3 4 5] ; 
y = y(x) 

如果你想使其成爲一種功能...要麼定義y裏面的功能或使其作爲輸入,如下所示:

function out = myfun(x,y) 

if ~isa(y,'function_handle') 
    error('input t should be a function handle') 
end 
out = y(x) ; 
end 


y = @(x) x.^2 ; 
x = [1 2 3 4 5] ; 
out = myfun(x,y) 
相關問題