size of matrices in a struct

6 visualizaciones (últimos 30 días)
Chris Dan
Chris Dan el 29 de Feb. de 2020
Comentada: Chris Dan el 1 de Mzo. de 2020
Hello
I have this struct
I want to make a loop to add all the sizes of matrices inside it automatically, or is there any more efficient ay other than loops ? I have made such a code, but not getting correct answers
a =0
for i = 1:1: size(S_1,1)
a = size(S_1(i).IndivualStiffnessMatrix,1)
a = a+a
end
Is it correct?

Respuesta aceptada

per isakson
per isakson el 1 de Mzo. de 2020
"add all the sizes of matrices" , but your code adds the heights (i.e. the number of rows). What exactly do you mean by "all sizes" ?
See arrayfun, Apply function to each element of array, and run this example, which adds the heights
>> S_1(4,1).IndivualStiffnessMatrix = sparse(magic(5));
>> S_1(1,1).IndivualStiffnessMatrix = sparse(magic(2));
>> S_1(2,1).IndivualStiffnessMatrix = sparse(magic(3));
>> S_1(3,1).IndivualStiffnessMatrix = sparse(magic(4));
>> a = sum( arrayfun( @(s) size(s.IndivualStiffnessMatrix,1), S_1 ) )
a =
14

Más respuestas (2)

David Hill
David Hill el 29 de Feb. de 2020
a =0;
for i = 1:1: size(S_1,2)
a = a+size(S_1(i).IndivualStiffnessMatrix,1);
end
  1 comentario
Chris Dan
Chris Dan el 1 de Mzo. de 2020
your answer is great and works, but the other answer is just a one liner
hope it is okay

Iniciar sesión para comentar.


dpb
dpb el 29 de Feb. de 2020
A loop is involved, yes, but you can write it w/o coding the loop explicitly.
Part depends upon just what it is you want; what your loop above does is add up the number of rows in each, which isn't the total number of elements.. Your answer is wrong because you also overwrite your sum every pass through the loop instead of saving it.
a=0;
for i = 1:1: size(S_1,1)
a = a+size(S_1(i).IndivualStiffnessMatrix,1);
end
would return that number...altho a isn't a very descriptive variable name.
To get the total number of elements in all the arrays,
N=sum(arrayfun(@(x)numel(x.IndivualStiffnessMatrix),S));
arrayfun of course ends up as a loop internally, just without explicitly writing the for...end so can be a one-liner if the content of the body can be expressed as anonymous function as here. Or, of course, for more complicated cases one can incorporate any function by writing an m-file.
The above is specific for the given struct and field; one could make somewhat more generic if were more than one field in the struct by also passing the field name.
N=sum(arrayfun(@(x,f)numel(x.(f)),S,repmat('x',size(S))));
where the second array input is the field name expanded to same size as the struct array since, unfortunately, arrayfun doesn't have automagic element expansion.

Categorías

Más información sobre Loops and Conditional Statements 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