How to plot a 1 x 1 struct with 175 fields in Matlab
12 views (last 30 days)
Show older comments
Michael Molyneaux-Francis
on 24 Jul 2018
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 Comments
Accepted Answer
Stephen23
on 27 Jul 2018
Edited: Stephen23
on 27 Jul 2018
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
3 Comments
More Answers (1)
Adam Danz
on 24 Jul 2018
Edited: Adam Danz
on 24 Jul 2018
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 Comments
Stephen23
on 27 Jul 2018
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)
See Also
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!