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!