loop for every field of a structure array

16 次查看(过去 30 天)
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

回答(1 个)

Yazan
Yazan 2021-7-24
编辑:Yazan 2021-7-24
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 个评论
Harry Smith
Harry Smith 2021-7-25
Thanks! but how can i store my calculations in a NaN matrix 500x1000?
so, as a result I would like to get a matrix with my values + nan values inside and fill it for every loop.
Yazan
Yazan 2021-7-26
编辑:Yazan 2021-7-26
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by