필터 지우기
필터 지우기

For loop with file number

조회 수: 4 (최근 30일)
Isma_gp
Isma_gp 2018년 9월 6일
편집: Stephen23 2018년 9월 6일
I have a for loop as follows:
for ii=1:n_lines
g(ii,:) = data.file_1.maximum(ii,:);
end
I would like to include this for loop into an outer for loop that changes the file number from the structure i.e. file_1, file_2, file_3 etc.
Can I get some help here? Thanks

채택된 답변

Stephen23
Stephen23 2018년 9월 6일
편집: Stephen23 2018년 9월 6일
This can be done with dynamic fieldnames:
for jj = 1:numberOfFields
fld = sprintf('file_%d',jj);
for ii = 1:n_lines
g(ii,:) = data.(fld).maximum(ii,:);
end
...
end
But this is a complex way to store and access your data. Accessing the fieldnames like this, and the required conversion from numeric to char, just makes your code more complex and slows down your code: a much simpler and more efficient way to design your data would be to use a non-scalar structure, then you can simply use indexing directly and efficiently:
for jj = 1:numberOfFields
for ii = 1:n_lines
g(ii,:) = data.file(jj).maximum(ii,:);
end
...
end
And probably avoiding using nested structures altogether would be a better way to design your data:
for jj = 1:numel(data)
data(jj).maximum
data(jj).file
data(jj).data
end
then you could simplify the code that accesses the data, by doing things like this:
g = vertcat(data.maximum)
and you will get all of the maximum matrices concatenated into one numeric array, without any loops or slow dynamic fieldnames. Better data design makes code simpler and more efficient.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by