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

9 vues (au cours des 30 derniers jours)
MARGE
MARGE le 19 Oct 2021
Commenté : MARGE le 22 Oct 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)
Thanks in advance for your suggestions

Réponse acceptée

Kelly Kearney
Kelly Kearney le 19 Oct 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

Plus de réponses (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov le 19 Oct 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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by