MATLAB: Create single variable from workspace variables

matlab 2012

I have many variables in the form (:,1) with different names in my workspace. What i want to achieve is to write a script that generates me a single variable in a table form with the values of any variable in columns with the name of the variable on top of the column. Somehow this script should go to the first variable in the workspace and store the content and the name in the generated variable in (:,1), the second in (:,2) and so on.
What i am missing is exactly the idea/way how to achieve that the script gets the variables one by one in the order in which they are in the workspace. Has anyone of you an idea?

Best Answer

Hi Juri,
You can get the names of all variables in your workspace using 'who' and you can access the variables with the corresponding names with 'eval'.
I am providing the code for your problem assuming all the variables in your workspace are of same dimensions (column arrays).
clc;
clear;
one=randi(100,10,1); %creating random number column arrays.
two=randi(100,10,1); %You can remove these three lines along with the clc and clear on top.
three=randi(100,10,1);
k=who; %getting the names of all the variables in workspace.
len=length(k); %calculating the number of rows(variables).
y=[];
for i=1:len
if(i==1)
y=eval(k{i});
else
y=[y eval(k{i})]; %creating a matrix from the variables.
end
end
t=array2table(y,'VariableNames',k') %creating the table from the matrix with the variables names on top of the coulumn.
't' here is the final table you wanted.
Hope this clears your query.
Thanks,
Aditya.