apply cellfun for specified rows of each cell
18 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Majid Mostafavi
le 19 Déc 2019
Modifié(e) : Adam Danz
le 20 Déc 2019
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?
0 commentaires
Réponse acceptée
Adam Danz
le 19 Déc 2019
Modifié(e) : Adam Danz
le 20 Déc 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);
>2x faster than cellfun.
mu = nan(size(a));
for i = 1:numel(a)
mu(i) = mean(a{i}(rows{i}));
end
2 commentaires
Plus de réponses (1)
Image Analyst
le 20 Déc 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 commentaire
Adam Danz
le 20 Déc 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.
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!