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 个评论

I tried the above technique.
s(out7).val = xf;
out7 gets value from for out7 = 11.8:1:15.8
error: Subscript indices must either be real positive integers or logicals.
Values used for indices cannot have fractional parts: they must be positive integers.
Is 11.8 a positive integer, or does it have a fractional part ?
Can this technique or other used for decimal numbers ?
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 的更多信息

提问:

2016-6-20

编辑:

2016-6-20

Community Treasure Hunt

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

Start Hunting!

Translated by