Borrar filtros
Borrar filtros

How to use loop in Anonymous functions?

5 visualizaciones (últimos 30 días)
Xiaohan Du
Xiaohan Du el 15 de Dic. de 2016
Comentada: Xiaohan Du el 15 de Dic. de 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!

Respuesta aceptada

José-Luis
José-Luis el 15 de Dic. de 2016
Editada: José-Luis el 15 de Dic. de 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)

Más respuestas (1)

Adam
Adam el 15 de Dic. de 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 comentario
Xiaohan Du
Xiaohan Du el 15 de Dic. de 2016
Thanks! There is a way to do it with anonymous function.

Iniciar sesión para comentar.

Categorías

Más información sobre Operating on Diagonal Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by