Automated concatenation of variables into matrix then separation of matrix into variables containing original variable names
1 view (last 30 days)
Show older comments
Hi,
I have a .mat file with several variables listed in the Workspace. I would like to 1) concatenate the variables into a matrix where each variable is a column, 2) convert the columns back to variables with their original names. Since I don't always know the variable names or the number of variables in the workspace, I need this process to be automated. I was thinking of doing something like this:
origvarnames = who;
for i = 1:length(origvarnames)
data(:,i) = ?variable?(i)
end
% where ?variable? is the nth variable in the workspace.
% after some work is done to the values within 'data' the columns need to go back into variables
for j = 1:length(origvarnames)
?variablename? = data(:,j)
end
% where the variablename could maybe come from the 'origvarnames' variable?
Could anyone fill in blanks or inform me of any useful functions for this process? If I am way off with my method then please tell me how you would carry out this procedure.
Thanks,
Dylan
1 Comment
Matt Fig
on 10 Jun 2011
What is the point of converting them to a matrix, then converting them back? What do you expect to gain from this at the end? In other words, if you already have them as separate variables, why go through the two steps to get them back as separate variables??
Accepted Answer
Fangjun Jiang
on 10 Jun 2011
It can be done but I am not sure if this is really necessary to solve your original problem. The following example assumes all your data is column vector (nx1 array). Step through to see the effect and see if you understand every one of them.
clear all;
a=(1:10)';
b=(100:10:150)';
c=rand(3,1);
Vars=whos;
data=[];
for k=1:length(Vars)
data=[data;eval(Vars(k).name)];
end
data=2*data;
for k=1:length(Vars)
assignin('base',Vars(k).name,data(1:Vars(k).size(1)));
data(1:Vars(k).size(1))=[];
end
More Answers (2)
Paulo Silva
on 10 Jun 2011
%without any verification of the format of all variables
a=[1 2 3]
b=[4 5 6]
lvar=who;
c=cell2mat(cellfun(@eval,lvar,'uni',false))'
0 Comments
Walter Roberson
on 10 Jun 2011
Are all of the matrices the same length? Could cell matrices be used?
The most natural approach would seem to be to use a structure with dynamic field names: is there reason not to use that?
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!