Using a for loop to access the correct fields in a struct

2 Ansichten (letzte 30 Tage)
10B
10B am 21 Nov. 2016
Kommentiert: 10B am 21 Nov. 2016
Hello Community,
I have a little query here (hopefully!) I am simply trying to ask the for loop to run through a struct ('Ss.') with various fields named pl1, pl2, pl3 etc. and work out the standard deviation for each field and assign to a new field named Ss.Sdpl for the same number of fields - 'i'.
for i = 1:N
Ss.Sdpl(i) = std(Ss.pl(i));
end
Unfortunately it returns the error: Reference to non-existent field 'pl', which of course I understand, but how should I write the syntax to run through Ss.pl 1, Ss.pl 2, Ss.pl 3 etc?
Any help would be much appreciated...
10B.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 21 Nov. 2016
Ss.Sdpl(i) = std(Ss.(sprintf('pl%d', i))) ;
  1 Kommentar
10B
10B am 21 Nov. 2016
Excellent - many thanks Walter. I completely forgot about having to 'print' the field number. A great help.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by