# How do I create a for loop with fields of structures?

조회 수: 8 (최근 30일)
MARGE . 2021년 10월 19일
댓글: MARGE . 2021년 10월 22일
Hello. Im not an expert using matlab and this is my first time working with data in structures.
I have a structure that has another structure inside (see attached pictures) and I want to calculate the percentage of data that remain after filtering, my first approach is:
nt= length(Global_Data.FilteredData)
for i=1:nt
F= length(Global_Data.FilteredData(i).DTTM)
R= length(Global_Data.FreeAna_data(i).DTTM)
P= (F/R)*100
end
But with these I only get one value of P, and I need the percentage for each item (118)

댓글을 달려면 로그인하십시오.

### 채택된 답변

Kelly Kearney 2021년 10월 19일
In your current code, you're saving over P on each iteration of the loop. Instead, save to an array:
nt= length(Global_Data.FilteredData);
P = zeros(nt,1);
for i=1:nt
F= length(Global_Data.FilteredData(i).DTTM)
R= length(Global_Data.FreeAna_data(i).DTTM)
P(i)= (F/R)*100
end
##### 댓글 수: 1표시 없음숨기기 없음
MARGE 2021년 10월 22일
Thanks a lot! :)

댓글을 달려면 로그인하십시오.

### 추가 답변 (1개)

Sulaymon Eshkabilov 2021년 10월 19일
You can try to work with fieldnames() and getfield() names, e.g.:
Fnames = fieldnames(Global_Data);
for ii = 1:length(Fnames)
Fi = getfield(Global_Data,Fnames{ii});
...
P = ...;
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