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)= ..;

Respuestas (1)

Stephen23
Stephen23 el 20 de Jun. de 2016
Editada: Stephen23 el 20 de Jun. de 2016
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
Amod Tambe el 20 de Jun. de 2016
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.
Stephen23
Stephen23 el 20 de Jun. de 2016
Editada: Stephen23 el 20 de Jun. de 2016
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 ?
Amod Tambe
Amod Tambe el 20 de Jun. de 2016
Can this technique or other used for decimal numbers ?
Stephen23
Stephen23 el 20 de Jun. de 2016
Editada: Stephen23 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.

Iniciar sesión para comentar.

Categorías

Preguntada:

el 20 de Jun. de 2016

Editada:

el 20 de Jun. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by