loop for every field of a structure array

조회 수: 32 (최근 30일)
Harry Smith
Harry Smith 2021년 7월 24일
편집: Yazan 2021년 7월 26일
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에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by