How to assign a variable value as structure name?
显示 更早的评论
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)= ..;
回答(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 个评论
Amod Tambe
2016-6-20
Amod Tambe
2016-6-20
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!