Clear Filters
Clear Filters

apply cellfun for specified rows of each cell

16 views (last 30 days)
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?

Accepted Answer

Adam Danz
Adam Danz on 19 Dec 2019
Edited: Adam Danz on 20 Dec 2019
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

More Answers (1)

Image Analyst
Image Analyst on 20 Dec 2019
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 Comment
Adam Danz
Adam Danz on 20 Dec 2019
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.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!