size of matrices in a struct
10 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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 个)
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 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!