How to add variables in workspace with names derived from a char array and corresponding values stored in a double array

조회 수: 3 (최근 30일)
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
harshpurohit11
harshpurohit11 2018년 8월 17일
편집: harshpurohit11 2018년 8월 17일
Stephen, thanks for the link, however I was not able to make eval work for me for my given problem at hand. I tried doing the following and i got an error saying "scripted assignment dimension mismatch"
for i = 1:length(col_names)
eval('col_names(i,1:end) = data(:,i)');
end
James Tursa
James Tursa 2018년 8월 17일
편집: James Tursa 2018년 8월 17일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Honglei Chen
Honglei Chen 2018년 8월 17일
Here is an example
col_names = ['time ';'speed'];
data = [0 1;2 3;4 5];
for m = 1:2
eval(sprintf('%s = data(:,m)',col_names(m,:)));
end
HTH
  댓글 수: 3
Honglei Chen
Honglei Chen 2018년 8월 17일
I have no issue running this code. Can you clear your workspace and try again? This is just an example showing how this can be done.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2018년 8월 17일
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

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품


릴리스

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by