How to take a max of a value in a struct

5 ビュー (過去 30 日間)
Brooke Allison
Brooke Allison 2020 年 7 月 24 日
コメント済み: dpb 2020 年 7 月 24 日
Hi there,
This is my second week coding in Matlab so please go easy on me.
I'm currently trying to find the max, min, and mean of thirteen materials that will soon grow to hundreds, so I need to set up the code in a loop.
So, I'm not sure but it seems like the only way to call my data into a for loop is to start with it in a large matrix, and then call whatever parts are needed each iteration, rather than calling a variable v(i) each iteration. I've done that but then the only way I have found to save each material separately is to save it in a struct. That works fine, I can create my struct with all the separate materials' data. Now I just need to take the max, min, etc. of each field in the struct. For some reason, even after lots of research, I am not finding a way to do that. Even if I do, must I save the maximums in another struct? I would like to save the max as a variable max(i) and then call that variable further on in another for loop during my data analysis but I know that won't work...
alldata = [m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13];
for i=1:13
scan(i).data=alldata(:,((50*(i-1))+1):(50*i));
maxfield(i) = (max(scan(i).data,:));
end
  1 件のコメント
dpb
dpb 2020 年 7 月 24 日
alldata = [m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13];
Almost certainly here's indication you've not set up the proper data structure for the problem. Virtually always the existence of a set of variables varying only by a subscript or other metadata to differentiate them is not the proper direction to follow.
Having that set of variables named is what prevents being able to reference them effectively with code.
Go back to the beginning and show us what kinds of data you have and how it is to be obtained, and more than likely can lead to a much more generic and simply impemented solution.
Without knowing anything more, have you looked at the MATLAB table class?

サインインしてコメントする。

回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2020 年 7 月 24 日
One way to do this
PropertyNames={'Name','Weight','Strength'};
Data={'Metal',100,100;
'Plastic',50,50;
'Paper',1,1};
Material=cell2struct(Data,PropertyNames,2);
In Command Window
>> Material(1)
ans =
struct with fields:
Name: 'Metal'
Weight: 100
Strength: 100
>> min([Material.Weight])
ans =
1
>> mean([Material.Strength])
ans =
50.3333

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by