Name arrays based on a variable

98 views (last 30 days)
mael thevenot
mael thevenot on 9 Dec 2019
Commented: Stephen23 on 10 Dec 2019
Hi,
I would like to create and fill array, which names are based on a variable.
Right now I manage to create and fill arrays, simply like this :
This_array(1) = 8;
This_other_array(4) = 12;
So I create the array and at the same time fill the index of the array that I want.
But what I'm trying to do is like that, to give an idea :
var = 'B'
[var, This_array](1) = 8
[var, This_other_array](4) = 8
So this do not work it's just an exemple to illustrate what I'm tryiing to do, like dynamically change the name of created arrays based on a variable.
Here the variable var is a char (idk why but that's what "class" tell me).
This code is in a for loop, an I would like to obtain an array called "B_This_array", or "C_This_array" based on the variable.
I've tried numerous ways and can't manage to make it work.
Thanks.
  1 Comment
Stephen23
Stephen23 on 10 Dec 2019
"...dynamically change the name of created arrays based on a variable."
Which is one way that beginners force themselves into writing slow, complex, buggy code:
It seems that you are trying to force meta-data into a variable name. Meta-data is data, and data should be stored in variables, not in variable names.
Note that indexing is neat, simple, and very efficient. You should probably use indexing.

Sign in to comment.

Answers (1)

Rik
Rik on 9 Dec 2019
The reasons why naming variables dynamically can be found here. It sounds like you are looking for the features a struct will provide you.
  3 Comments
Stephen23
Stephen23 on 10 Dec 2019
mael thevenot's "Answer" moved here:
Ok so I managed to do what I wanted with nested structures and indexing. I created structure and then dynamicaaly access its field with :
fns = fieldnames(A);
A.(fns{3})
So with nested structs I have things like :
if ....
var 1 = 2;
fns2 = fieldnames(s.(fns{var1}));
var 2 = 4;
fns3 = fieldnames(s.(fns{va1}).(fns2{var2}));
...
end
s.(fns{var1})(1).(fns2{var2})(1).(fns3{var3})(1).(fns4{var4})(1) = my_value;
And actually it's way more neat and short to do like this :)
Thank you very much for your help !

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!