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

3 visualizzazioni (ultimi 30 giorni)
MARGE il 19 Ott 2021
Commentato: MARGE il 22 Ott 2021
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)
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Kelly Kearney il 19 Ott 2021
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 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
MARGE il 22 Ott 2021
Thanks a lot! :)

Accedi per commentare.

### Più risposte (1)

Sulaymon Eshkabilov il 19 Ott 2021
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
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by