How to plot a 1 x 1 struct with 175 fields in Matlab
9 次查看(过去 30 天)
显示 更早的评论
Now, my workspace has ans as a 1 x 1 struct. The 1 x 1 struct has 175 fields, with 5 extra fields as text*. Thus a total of 180 fields.
I need help plotting my data. In my 1 x 1 struct, I have Segment1 to Segment175. In each, there is a another subfolder called data, in which there are 10000 rows and 2 columns of values. How do I plot ans.Segment1.data, ans.Segment2.data, ans.Segment3.data, ... ,ans.Segment175.data into ONE graph?
*Please let me know if the 5 text fields for each segment data confuses matlab in some kind of way.
2 个评论
采纳的回答
Stephen23
2018-7-27
编辑:Stephen23
2018-7-27
Unfortunately putting numbers into fieldnames like that makes it all rather tricky, because putting (meta)-data into the fieldnames makes them awkward to handle. The data should have been stored in a non-scalar structure, because indexing is much simpler and more efficient.
As Adam Danz wrote, using ans is a bad idea. Better call your structure s or something more explanatory of its contents. Then you could use dynamic fieldnames like this:
s.Segment1.data = [0,0.00034;0.0001,0.000176;0.0002,0.000176;0.0003,0.000176;0.0004,0.00034;0.9995,0.000505];
s.Segment2.data = [1,0.000176;1.0001,0.000176;1.0002,0.000176;1.0003,0.000669;1.0004,0.00034;1.0005,0.00034];
... all the other fields
s.otherfield = 'blah';
for k = 1:175
fnm = sprintf('Segment%d',k);
plot(s.(fnm).data(:,1),s.(fnm).data(:,2))
hold on
end
Or a a bit neater and clearer would be to use a temporary variable:
for k = 1:175
fnm = sprintf('Segment%d',k);
tmp = s.(fnm).data;
plot(tmp(:,1),tmp(:,2))
hold on
end
更多回答(1 个)
Adam Danz
2018-7-24
编辑:Adam Danz
2018-7-24
This should get you halfway there. The other half depends on how you're plotting the data which isn't described.
Instead of 'ans', I'll call your structure 's' (never use 'ans' as a variable name).
sArray = struct2array(s);
sMat = [sArray.data];
If you want all of your data organized vertically into two columns,
cell2mat({sArray.data}');
Use reshape() if you need your data organized differently.
If you're plotting in a loop,
sCell = {sArray.data};
for i = 1:length(sCell)
...sCell{i}...
end
3 个评论
Stephen23
2018-7-27
Note that struct2array is not a MATLAB function (it was used in some toolbox several years ago).
Note that
cell2mat({sArray.data}');
would be simpler as:
vertcat(sArray.data)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!