apply cellfun for specified rows of each cell

16 次查看(过去 30 天)
Hello
I have a cell containing double matrix of each row as example:
a={[1;2;4;5;2;3];[3;2;1;4;5;9;4;1;2];[];[2;3;4];[1;2;4;5;6]}
I want to apply CELLFUN at each cell for specified rows of each matrix for example row number from 2:4 of first matrix and rows from 3:6 of second and....
I wrote a loop for this but wonder if there would be easier way by using cellfun(@mean a) for specified row numbers of each matrix of a, do you know any?

采纳的回答

Adam Danz
Adam Danz 2019-12-19
编辑:Adam Danz 2019-12-20
rows is a cell array the same size and shape at a containing vectors of row numbers.
a={[1;2;4;5;2;3];[3;2;1;4;5;9;4;1;2];[];[2;3;4];[1;2;4;5;6]}
rows = {2:4, 3:6, [], 1:2, 2:4}';
mu = cellfun(@(x,i)mean(x(i)), a, rows);
Loop method (suggested by Image Analyst)
>2x faster than cellfun.
mu = nan(size(a));
for i = 1:numel(a)
mu(i) = mean(a{i}(rows{i}));
end

更多回答(1 个)

Image Analyst
Image Analyst 2019-12-20
As an aside, see Loren's blog: Which Way to Compute: cellfun or for-loop?
At one point she (by the way, she's the first employee of the Mathworks, if I remember correctly what Cleve Moler (founder) told me in person) says "If I know the number of inputs and outputs and the function I want to apply elementwise, I generally write an explicit loop." I tend to agree because for loops are usually more intuitive and much more easily understood. They're not as compact as cellfun() but that means they are usually not as cryptic. Anyway, when you write the function that cellfun() must use, it's often the same algorithm -- it's just that with a for loop you need to enclose that code in a for loop instead of passing it to the cellfun() function. And to me, having understandable, maintainable code (that others have written and I've inherited) is much more inportant than compactness.
  1 个评论
Adam Danz
Adam Danz 2019-12-20
Thanks for bringing this up, Image Analyst. I have a bias toward 1-liners but I also agree that loops are avoided too often.
I'm going to add the loop method to my answer.
In this case, the loop is much faster than the cellfun line. I timed each 10k times using tic/toc and based on the median times, the loop is 2.3x faster and that difference is highly significant based on 95% CIs.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by