How to add variables in workspace with names derived from a char array and corresponding values stored in a double array
Mostra commenti meno recenti
char array col_names = [time; speed; distance...] and double array data = [0;1;2;3... ,10;20;30;40.. ,5;6;7;8...]. col_names is a mXn matrix and data is a kXm matrix. I need to generate workspace variables time, speed, distance.. with their value content coming from data matrix
3 Commenti
Magically generating or accessing variable names is how some beginners force themselves into writing slow, complex, buggy code. Read these to know why:
harshpurohit11
il 17 Ago 2018
Modificato: harshpurohit11
il 17 Ago 2018
James Tursa
il 17 Ago 2018
Modificato: James Tursa
il 17 Ago 2018
The syntax should have been:
for i = 1:size(col_names,1)
eval([col_names(i,1:end) ' = data(:,i)']);
BUT ... you are missing the entire point of Stephen's post. This is a very poor programming practice. Read Stephen's link to see why and to discover better methods of writing your code that are easier to read, maintain, etc.
Risposta accettata
Più risposte (1)
Steven Lord
il 17 Ago 2018
Instead of dynamically creating variables, I recommend creating a table array. The variables (columns) in a table are named so you can reference the data using those names.
>> R = randi([-10 10], 15, 3);
>> T = array2table(R, 'VariableNames', {'time', 'speed', 'distance'});
>> T.distance ./ T.time
Categorie
Scopri di più su Logical in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!