size of matrices in a struct
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Chris Dan
am 29 Feb. 2020
Kommentiert: Chris Dan
am 1 Mär. 2020
Hello
I have this struct
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/274419/image.jpeg)
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?
0 Kommentare
Akzeptierte Antwort
per isakson
am 1 Mär. 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" ?
>> 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
0 Kommentare
Weitere Antworten (2)
David Hill
am 29 Feb. 2020
a =0;
for i = 1:1: size(S_1,2)
a = a+size(S_1(i).IndivualStiffnessMatrix,1);
end
dpb
am 29 Feb. 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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Structures 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!