Problem with data indexing in nested structure
Show older comments
Hi everyone,
I have a nested structure(see attacted file egc.mat), and I'd like to store value based on their 'source', as defined in the structure, if it exists. Otherwise use NaN
As you can see, not all of the sources are available for each row, for example, in Z.hours(2).AA, source 'ui' is missing
Also note that the order of source will change, for example, in Z.hours(1).AA, source 'sg' and its respective value are in the first row, while in Z.hours(2).AA, they are in the second row.
In the end, I want things in a matrix, so something like this,
sg=[1 3.25;
2 2.601;
3 0.1273];
ns=[1 4.07;
2 2.6521;
3 2.8242];
mm=[1 4.01;
2 1.3728;
3 0.6847];
ui=[1 3.56;
2 NaN;
3 2.6219];
I tried the following command
sg=zeros(3,2);
for i=1:3
sg(i,1)=i;
sg(i,2)=Z.hours(i).AA(source=='sg')
end
It doesn't work because I didn't access the data correctly.
So is there any good solution for that?
Thank you
Accepted Answer
More Answers (1)
Bob Thompson
on 16 Jul 2019
0 votes
In my experience, nested structures do a really good job of intuitively organizing data, but are difficult to work with in matlab.
Are you getting a specific error message? If so, please post it in it's entirety.
'It doesn't work because I didn't access the data correctly.'
I don't know exactly what this means, but I'm going to hazard a guess and say the error message gave you something along the lines of, 'function was looking for one result, but returned three instead.' You can try getting around this using a find function, but I can't guarentee it will work. Others on here can give a more technical explanation of why nested loop indices generally need to be pretty specific. In short, you cannot make a call like AA(:).source because the computer actually sees AA(1), AA(2), AA(3),..., AA(n).source which doesn't really make any sense to it. You can sometimes use [] to get around this, but that is usually only successful for the final layer, not an intermediary.
loc = find([Z.hours(i).AA(:)]=='sg'); % Almost certain this won't produce anything
2 Comments
Shuo Zhang
on 17 Jul 2019
Bob Thompson
on 17 Jul 2019
I'm assuming you have source defined as part of the Z structure. Using (source == 'sg') is not going to work because source is not defined as a variable, but as a field of the variable Z.
Using 'source' == 'sg' is not going to work because you are comparing the two strings 'source' and 'sg' which will return the matrix dimension error because one has six elements and one has two elements.
Categories
Find more on Loops and Conditional Statements 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!