How do I use a loop to isolate column vectors of a matrix into separate variables

2 views (last 30 days)
What I'm trying to do is strip the columns from an excel file into separate variables for analysis. I know how to do it if I know the number of columns, then I can do it manually. What i would like is to do it using a for loop. This is what I have so far:
data = xlsread(fullfile(path,file));
N = size(data,2);
M = size(data,1);
for i = 1:N
varname = strcat('data',num2str(i));
eval(sprintf('%s = %f',varname,data(:,i)));
end
any help would be greatly appreciated.
Thanks, George

Accepted Answer

dpb
dpb on 4 Jun 2014
  7 Comments
Joseph Cheng
Joseph Cheng on 4 Jun 2014
ah i see for the eval part. I quickly did it with a test with data=magic(10). and didn't use the sprintf. but i agree it isn't the best method. Only way i can think this applicable is if the columns are specific telemetry that may not be in the same order each time the file is created and the order is pulled from another file (ie header file). But again if you have the order you can use that to look at which section of the block of data. there is very limited cases where one needs to generate these unknown variables.
dpb
dpb on 4 Jun 2014
Generating the arrays isn't that big of a deal; it's the resultant mess of how is one then going to write robust maintainable code making use of them that is where the real rub lies.
Once he's got all those variables 'poofed' into the workspace, now he's got to dynamically continue to generate the names and eval every command; he can no longer just write generic code directly for almost anything.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!