Borrar filtros
Borrar filtros

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

2 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Jan
Jan el 2 de Abr. de 2022
Editada: Jan el 2 de Abr. de 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 comentario
Sokratis Panagiotidis
Sokratis Panagiotidis el 2 de Abr. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by