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

조회 수: 6 (최근 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 CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by