How can I pass an array to Matlab function?

Hi all, Would you please advise how can I pass an array to Matlab function so that I can use each element in the array to calculate different outputs? Kind regards,

回答 (2 件)

James Tursa
James Tursa 2018 年 7 月 5 日
編集済み: James Tursa 2018 年 7 月 5 日

3 投票

This is going to depend on whether the function in question is vectorized or not. E.g., suppose the function is vectorized:
function result = myfun(x)
result = x.^2;
end
Then you would call it like this:
x = whatever
y = myfun(x);
But suppose the function is not vectorized:
function result = myfun(x)
result = x^2; % <-- Note the use of ^ instead of .^
end
Then you would be stuck with a loop:
x = whatever
y = zeros(size(x));
for k=1:numel(x)
y(i) = myfun(x(i));
end
Or you could use the arrayfun() function (with the loop hidden in the background):
y = arrayfun(@myfun,x);
The above examples assume that the output of the function for a scalar input is also scalar. If that is not the case then different code would be needed to store the results.
Keen
Keen 2018 年 7 月 8 日

0 投票

Many thanks, it was really helpful.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2018 年 7 月 5 日

回答済み:

2018 年 7 月 8 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by