Effacer les filtres
Effacer les filtres

How to use loop in Anonymous functions?

5 vues (au cours des 30 derniers jours)
Xiaohan Du
Xiaohan Du le 15 Déc 2016
Commenté : Xiaohan Du le 15 Déc 2016
Hi all,
I have a 2 by 2 cell 'dblk' like this:
dblk =
[4x4 double] [4x4 double]
[4x4 double] [4x4 double]
which contains 4 by 4 matrix in each cell block. Now I'd like to apply the same function on each block. The function sums all elements on all diagonal line, not just the main diagonal. I wrote the function as an Anonymous function:
diagsum = @(x) [sum(diag(x, -3)) sum(diag(x, -2)) sum(diag(x, -1)) ...
sum(diag(x, 0)) sum(diag(x, 1)) sum(diag(x, 2)) sum(diag(x, 3))];
Then I'm able to apply cellfun on dblk to get the summation result:
dblksum = cellfun(diagsum, dblk, 'UniformOutput', false);
The problem is in the Anonymous function 'diagsum', the sum(diag(x, n)), n starts from -3 to 3 cause the input is a 4 by 4 matrix, how can I make it apply to any matrix size?
Many thanks!

Réponse acceptée

José-Luis
José-Luis le 15 Déc 2016
Modifié(e) : José-Luis le 15 Déc 2016
No need for a loop. You could define diagsum as follows, which should work for any square array:
n = 5;
values = rand(n);
diagsum = @(x) accumarray(reshape(bsxfun(@plus,(n:-1:1)',0:n-1),[],1),x(:))';
diagsum(values)
  1 commentaire
Xiaohan Du
Xiaohan Du le 15 Déc 2016
Thanks! This is very clever!

Connectez-vous pour commenter.

Plus de réponses (1)

Adam
Adam le 15 Déc 2016
I would probably just use a regular function in a file and create a handle to that. There is a limit to what you can do in an anonymous function. Maybe there is a way, including size(x,1) to get the size of your matrix, but it isn't easy to add extra calls to sum(diag(...)) in response to that.
You could create the function as a string and use str2fun possibly, but I would not recommend doing that when you could just create a regular function that is easily readable, understandable and debugable.
  1 commentaire
Xiaohan Du
Xiaohan Du le 15 Déc 2016
Thanks! There is a way to do it with anonymous function.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Operating on Diagonal Matrices 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!

Translated by