Printing string as a variable

5 Ansichten (letzte 30 Tage)
rob
rob am 20 Sep. 2017
Beantwortet: Rik am 20 Sep. 2017
I have a table (mytable)with 'm' rows and I am trying to add multiple empty columns with names that are in ascending numerical order (variable_01var, variable_02var etc) :
for i = 1:16
number = sprintf('%02d',i);
variable = insertAfter('mytable.variable_var', '_', number)
sprintf(variable) = zeros(m,1);
end
I am not sure how to get the generated variable name printed as a variable though?
Any help much appreciated, thanks!
Rob
  3 Kommentare
rob
rob am 20 Sep. 2017
Thanks Rik, I am using the data type 'table'. Would you be able to advise how to do this? I.e. how to generate a set of columns with names defined in a for loop?
Stephen23
Stephen23 am 20 Sep. 2017
" I am trying to add multiple empty columns with names that are in ascending numerical order (variable_01var, variable_02var etc)"
Do NOT do this.
Read what the MATLAB documentation has to say about this: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array"
You should also read this:
and after that keep your data in one array and use indexing, or use a table.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Rik
Rik am 20 Sep. 2017
If your table is called mytable, you can create a new column the same way as you can add a field to a struct:
for i = 1:16
number = sprintf('%02d',i);
variable = insertAfter('variable_var', '_', number)
mytable.(variable) = zeros(m,1);
end
And why not use this:
for i = 1:16
variable = sprintf('variable_%02dvar',i);
mytable.(variable) = zeros(m,1);
end

Weitere Antworten (0)

Kategorien

Mehr zu Tables finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by