size of matrices in a struct

조회 수: 6 (최근 30일)
Chris Dan
Chris Dan 2020년 2월 29일
댓글: Chris Dan 2020년 3월 1일
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?

채택된 답변

per isakson
per isakson 2020년 3월 1일
"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

추가 답변 (2개)

David Hill
David Hill 2020년 2월 29일
a =0;
for i = 1:1: size(S_1,2)
a = a+size(S_1(i).IndivualStiffnessMatrix,1);
end
  댓글 수: 1
Chris Dan
Chris Dan 2020년 3월 1일
your answer is great and works, but the other answer is just a one liner
hope it is okay

댓글을 달려면 로그인하십시오.


dpb
dpb 2020년 2월 29일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by