Filter löschen
Filter löschen

How to use loop in Anonymous functions?

5 Ansichten (letzte 30 Tage)
Xiaohan Du
Xiaohan Du am 15 Dez. 2016
Kommentiert: Xiaohan Du am 15 Dez. 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!

Akzeptierte Antwort

José-Luis
José-Luis am 15 Dez. 2016
Bearbeitet: José-Luis am 15 Dez. 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)

Weitere Antworten (1)

Adam
Adam am 15 Dez. 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 Kommentar
Xiaohan Du
Xiaohan Du am 15 Dez. 2016
Thanks! There is a way to do it with anonymous function.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by