size of matrices in a struct
조회 수: 6 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
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" ?
>> 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
추가 답변 (2개)
David Hill
2020년 2월 29일
a =0;
for i = 1:1: size(S_1,2)
a = a+size(S_1(i).IndivualStiffnessMatrix,1);
end
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!