How to use loop in Anonymous functions?

9 ビュー (過去 30 日間)
Xiaohan Du
Xiaohan Du 2016 年 12 月 15 日
コメント済み: Xiaohan Du 2016 年 12 月 15 日
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!

採用された回答

José-Luis
José-Luis 2016 年 12 月 15 日
編集済み: José-Luis 2016 年 12 月 15 日
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 件のコメント
Xiaohan Du
Xiaohan Du 2016 年 12 月 15 日
Thanks! This is very clever!

サインインしてコメントする。

その他の回答 (1 件)

Adam
Adam 2016 年 12 月 15 日
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 件のコメント
Xiaohan Du
Xiaohan Du 2016 年 12 月 15 日
Thanks! There is a way to do it with anonymous function.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by