Clear Filters
Clear Filters

How to use loop in Anonymous functions?

5 views (last 30 days)
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!

Accepted Answer

José-Luis
José-Luis on 15 Dec 2016
Edited: José-Luis on 15 Dec 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)

More Answers (1)

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

Sign in to comment.

Categories

Find more on Operating on Diagonal 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!