Azzera filtri
Azzera filtri

Loop through data-struct and its sub-structs; Trouble with 'indexing' - error

2 visualizzazioni (ultimi 30 giorni)
Hi,
I have a data struct called "DATA" with N fields (let's say 5 in to make it easier on the mind). Each of these fields has two more fields, which have a big matrix.
I am trying to create a loop to go through these fields and select one certain column (each have names) of the matrix.
So let's say I go with DATA.N.second-field.columnOfChoice; That means I went with field #N of my struct 'DATA' and wanted to chose the second 'sub'-field of N, which is a matrix. Out of this matrix I am trying to get the values of a certain row, which has a certain name, which I am using instead of 'columnOfChoice'.
I am having trouble to include the variable N into the loop. My thought was to go something like this:
fn = fieldnames(DATA); % Gives me a cell of N fields, each containing the name of the name of field #N
for N = 1:length(fn)
x = DATA.fn(N).second-field.columnOfChoice1;
y = DATA.fn(N).second-field.columnOfChoice2;
% Should select the preferred column of the N-th DATA-field to plot
% them later on.
plot(x,y);
hold on;
end
I get the error
"Unrecognized field name "N".",
which is kinda weird as I have defined N in the loop earlier.
Ich think the issue might lie in the fact that fn gives me a cell array, meaning the entries are for instance {'One'}, {'Two'}, etc.
What would be a possible way to run a loop through all of the DATA fields and select the columns of choice. Wether it is to plot them or not is not that important, as I am trying to use them for multiple reasons.

Risposta accettata

Jan
Jan il 2 Apr 2022
Modificato: Jan il 2 Apr 2022
You want to use "dynamic field names". Then the field name must be included in parentheses:
x = DATA.(fn{N}).second-field.columnOfChoice1;
% ^ ^ ^^
In addition you need curly braces to address an element of the cell string fn.
".columnOfChoice1" is not a valid indexing in Matlab. Maybe you mean:
x = DATA.(fn{N}).second-field(:, columnOfChoice1);
  1 Commento
Sokratis Panagiotidis
Sokratis Panagiotidis il 2 Apr 2022
Okay, firstly THANK YOU!
Now to your addition:
Let's say 'second-field' is actually called 'b' and the column of Choice is 'height', so by plotting I would have made
y = DATA.(fn{N}).b.height;
and for x I'd make the lenght of the column, which let's say it's
x = DATA.(fn{N}).b.length;
So to plot them I always used
plot(x,y, '.'); % Needed them as dots instead of a line.
so I am not sure if I understand your comment on that.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by