Mapping a function over each cell in a cell array using arrayfun
5 次查看(过去 30 天)
显示 更早的评论
Hi,
I am trying to "map" a function over each cell in a cell array. For example, suppose that I have a cell array which is filled with vectors of the same length:
C=cell(2,2);
C(1,1)={[1,1]};
C(1,2)={[2,2]};
C(2,1)={[3,3]};
C(2,2)={[4,4]};
Now I wish to apply the built-in Matlab function "norm" to each element in the cell array and return the results in an array (a regular, numeric array/matrix). I tried the following:
myresult=arrayfun(@(M,N) norm(cell2mat(C(M,N))),1:size(C,1),1:size(C,2))
But of course this does not give me what I really want; it gives me the following:
myresult =
1.4142 5.6569
which is only the norm of the (1,1) element (note that sqrt(1.^2 + 1.^2) = 1.4142) and the norm of the (2,2) element (note that sqrt(4.^2 + 4.^2) = 5.6569). This is because in my code, by specifying M as 1:size(C,1) and N as 1:size(C,2), the function is only evaluated at (M,N)=(1,1) and (M,N)=(2,2).
Can you please help me to see how I can modify my code to take the norm of all the arrays stored in the cell array C?
Thanks in advance,
Andrew DeYoung
Carnegie Mellon University
0 个评论
采纳的回答
Walter Roberson
2011-5-10
myresult = arrayfun(@(c) norm(c{1}), C);
Or more compactly,
myresult = cellfun(@norm,C);
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Analysis 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!