Assess element in struct which filed name contains '.'

1 Ansicht (letzte 30 Tage)
Areum Lee
Areum Lee am 19 Okt. 2018
Bearbeitet: Stephen23 am 19 Okt. 2018
hello folks,
I am trying to get the elements from the multiple structs data. for example
a = data.x1.data(1)
when I try to loop this in for loop, I need to increase the number following by x for example
data.x1.data(1) data.x2.data(1)
so I simply used this
for i = 1:b;
data0(i,4) =(data.x(i).data(1))
end
but it keeps saying that 'Reference to non-existent field 'x'.'
How can I resolve this error? it doesn't have any problem when I use
data.x1.data(1)
hope anyone of you can guide me :(
thanks, Ali
  1 Kommentar
Stephen23
Stephen23 am 19 Okt. 2018
This syntax:
data.x(i)
trieds to access the i-th element of the field x. Your structure data does not contain the field x, so this will not work (unless you improve your data design to use a non-scalar structure).

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 19 Okt. 2018
Bearbeitet: Stephen23 am 19 Okt. 2018
You will need to use a dynamic fieldname:
for k = 1:b;
fld = sprint('x%d',k);
data.(fld).data
end
Your code would be simpler and more efficient if you just used a non-scalar structure, then you could just use indexing:
>> S(1).data = 1:3;
>> S(2).data = 4:6;
>> S(3).data = 7:9;
>> for k = 1:3, S(k).data(1), end
ans = 1
ans = 4
ans = 7
Personally I would also recommend avoiding using nested structures, as then you can use the very convenient comma-separated list syntax for handling multiple elements of the structure.
  1 Kommentar
Areum Lee
Areum Lee am 19 Okt. 2018
thank you very much for the quick answer. that's what I exactly wanted.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by