필터 지우기
필터 지우기

apply cellfun for specified rows of each cell

조회 수: 16 (최근 30일)
Majid Mostafavi
Majid Mostafavi 2019년 12월 19일
편집: Adam Danz 2019년 12월 20일
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
  댓글 수: 2
Majid Mostafavi
Majid Mostafavi 2019년 12월 20일
thanks for that, it worked properly
Adam Danz
Adam Danz 2019년 12월 20일
편집: Adam Danz 2019년 12월 20일
Glad I could help!

댓글을 달려면 로그인하십시오.

추가 답변 (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