Loop through data-struct and its sub-structs; Trouble with 'indexing' - error
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Jan
2022-4-2
编辑:Jan
2022-4-2
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);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!