loop for every field of a structure array
조회 수: 17 (최근 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
댓글 수: 0
답변 (1개)
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
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 Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!