Use string to index variables

Hello,
So far I have data that depend on several parameter, something like that
%data first index is the year 1 for 2021 2 for 2022
%data second index is the person 1 for Ana 2 for Bob
%data third index is 1 the size 2 the age
data[1,2,2]=43; %the age of BOB in 2021
I want something like this
data['2021','Bob','age']=43;
And ideally if I want to add someone else I could just do
data['2021','Camille','age']=55; %adding a new person
Is there any syntaxe in matlab that allows me to do that ?

4 comentarios

Stephen23
Stephen23 el 4 de Oct. de 2022
"Is there any syntaxe in matlab that allows me to do that ?"
You could use the fieldnames of a structure:
data.y2021.Bob.age = 43;
data.y2021.Camille.age = 55;
but a much better would be to use a table or non-scalar structure (and not force meta-data into fieldnames), e.g.:
S(1).year = 2021;
S(1).name = 'Bob';
S(1).age = 43;
S(2).year = 2021;
S(2).name = 'Camille';
S(2).age = 55;
This doesn't work for me because I'd like to do stuff like this
for i=['Bob','Alice']
dostuff(i)=data['2021',i,'age']
end
This works with my equivalence table with something like this but is way less lisible
for i=[1,2]
dostuff(i)=data[1,i,2]
end
Stephen23
Stephen23 el 4 de Oct. de 2022
Editada: Stephen23 el 4 de Oct. de 2022
Note that in MATLAB square brackets are a concatenation operator, so your code
['Bob','Alice']
is exactly equivalent to
'BobAlice'
"This doesn't work for me because I'd like to do stuff like this"
It works for me:
data.y2021.Bob.age = 43;
data.y2021.Alice.age = 55;
for name = ["Bob","Alice"]
data.y2021.(name).age
end
ans = 43
ans = 55
If you have a recent enough version, you could possibly use a dictionary:
Note that meta-data is data, and most tasks are easier to solve in MATLAB when data is stored in variables.
Matteo Bonhomme
Matteo Bonhomme el 4 de Oct. de 2022
It worked !!!
Thank you :)

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Productos

Versión

R2021a

Etiquetas

Preguntada:

el 4 de Oct. de 2022

Comentada:

el 4 de Oct. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by