How to assign a variable value as structure name?
Show older comments
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)= ..;
Answers (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 Comments
Amod Tambe
on 20 Jun 2016
Amod Tambe
on 20 Jun 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.
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!