loop for every field of a structure array
11 views (last 30 days)
Show older comments
Hello everyone!
I hope someone can help me.
I have a structure array with 5 fields. In every field, there is a matrix (240x4).
i'd like to create a for loop that can:
-select one field at a time
-select a column of that field
-perform calculations fot the values of that column
-save the results in a matrix of size (500x1000)
-start over with a new field
Unfortunatly i am not familiar with matlab. Can someone help me?
This is my code:
my structure array is called str
fn=fieldnames(str)
for i_field=1:numel(fn)
for i_column=1:4
nan_matrix=NaN(500x1000);
%my script
end
%How can i fill the nan_matrix with my results and save it?
end
0 Comments
Answers (1)
Yazan
on 24 Jul 2021
Edited: Yazan
on 24 Jul 2021
See an example below on how to get the fields of a structure, then access the data in each field.
% toy data: structure of two fields
s.data1 = randn(240, 4);
s.data2 = randn(240, 4);
% get the names of the fields
fields = fieldnames(s);
% loop over fields
for nfield=1:length(fields)
dat = getfield(s, fields{nfield});
% perform here whatever calculations you need
% example: get one column of the data in one field
c = dat(5, :);
end
2 Comments
Yazan
on 26 Jul 2021
Edited: Yazan
on 26 Jul 2021
Saving results in a matrix is a basic Matlab operation, so I assumed that even as a basic Matlab user, you would know how to do so. Anyways, it depends on how you want to save your results in the NaN matrix. If we assume that fields data (each is of size 240-by-4) should be concatenated vertically in the matrix NaN, then you can do the following:
clc, clear
% toy data: structure of two fields
s.data1 = zeros(240, 4);
s.data2 = ones(240, 4);
s.data3 = 2*ones(240, 4);
s.data4 = 3*ones(240, 4);
s.data5 = 4*ones(240, 4);
% get the names of the fields
fields = fieldnames(s);
% matrix to save the results
allRes = nan(500, 1000);
% loop over fields
for nfield=1:length(fields)
dat = getfield(s, fields{nfield});
% perform here whatever calculations you need on dat
% save the result in allRes
allRes((1:size(dat,1))+(nfield-1)*size(dat, 1), 1:size(dat, 2)) = dat;
end
See Also
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!