Threading part of a function over each element in a cell array

1 回表示 (過去 30 日間)
Andrew
Andrew 2011 年 5 月 19 日
Hi,
I would like to thread part of a function over each element in a cell array. I'm afraid I'm being totally non-descriptive, so let me give an example.
Suppose I have a cell array, with each cell containing a 1 by 2 vector:
mycellarray={[1 2],[3 4],[5 6]};
I have a function, which I will call myfun. myfun takes three arguments:
myfun(a,b,c)
where a, b, and c are scalars. Let n be some scalar, say n=9. I wish to evaluate the function myfun with a=n and with b and c taking the values given in the 1 by 2 vectors contained in mycellarray. So, I would like the result to be:
{myfun(i,1,2),myfun(i,3,4),myfun(i,5,6)}
In other words, I want, in a sense, to "thread" myfun over mycellarray, which contains the values of b and c.
Is there a way to do this that might be faster, or more elegant in terms of the code, than the following (that is, using a "for" loop):
mycellarray={[1 2],[3 4],[5 6]};
n=9;
newarray=zeros(1,length(mycellarray));
for i=1:length(mycellarray)
newarray(i)=myfun(n,mycellarray{i}(1),mycellarray{i}(2));
end
Thank you very much for your time!
Andrew DeYoung
Carnegie Mellon University

採用された回答

Sean de Wolski
Sean de Wolski 2011 年 5 月 19 日
The for-loop is probably the fastest way. You could also do:
newarray = cellfun(@(C)myfun(n,C(1),C(2)),mycellarray)
But I've found cellfun to always be slower than a well constructed for-loop. It might be different on your machine/version.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by