How to assign a variable value as structure name?
Mostrar comentarios más antiguos
I have many for loops and i wish to save the data in a sequence. By using variable value as structure name?
e.g for out=1:1:6 ... end
Struct( out).value( out)= ..;
Respuestas (1)
Use a non-scalar structure, which lets you use indexing to access the structure. Then your task is very simple:
>> S(1).name = 'anna';
>> S(1).age = 28;
>> S(2).name = 'bob';
>> S(2).age = 13;
>> S(3).name = 'catherine';
>> S(3).age = 99;
or in a loop:
for k = 1:N
S(k).name = '...';
S(k).age = [...];
end
And accessing the data is trivial
>> S(3).name
ans = catherine
There is even a syntax get all of the values at once:
>> [S.age]
ans =
28 13 99
>> {S.name}
ans = 'anna' 'bob' 'catherine'
Read the link I gave to learn how so access a non-scalar structure properly.
4 comentarios
Amod Tambe
el 20 de Jun. de 2016
Amod Tambe
el 20 de Jun. de 2016
MATLAB, like most programming languages in the history of computer science, only supports integer indices. To get around this you should put your values in a vector, and use the corresponding indices for your structure and vector:
vec = 11.8:1:15.8;
S(1).field = ...
S(2).field = ...
...etc
and then
vec(k)
S(k).field
contain corresponding values.
Categorías
Más información sobre Structures en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!