How do I rename a variable, as it changes in a Loop

I have .mat file. and first I load my variables (Data_1,Data_2....Data_60) using
for i=1:60
load(['matfiles/Data_',num2str(i),'.mat']);
end
I want to use a loop to write to a spreadsheet instead of writing this 60 times. so I do this
for i=1:60
xlwrite('saved_file.xls',Data_1, sheetName,'B3') // Data_1 is one of the variable loaded above.Needs to change to Data_2 and so on.
end
now the question is I want to dynamically change the name in Data_1 every iteration using the loaded files. How can I do this.

1 Comment

"I want to dynamically change the name in Data_1 every iteration using the loaded files. How can I do this."
Do NOT do this! Magically accessing/defining variable names is one way that beginners force themselves into writing slow, complex, buggy code. Read this to know why:
A much simpler and more efficient solution is to load the data into an output variable (which you should always be doing anyway, and then use struct2cell. Then your task is easy.

Sign in to comment.

 Accepted Answer

This is easy, as long as there is only one variable loaded from each .mat file:
for k = 1:60
F = sprintf('Data%d.mat',k);
P = fullfile('matfiles',F);
S = load(F);
C = struct2cell(S);
N = sprintf('sheet%d',k);
xlswrite('saved_file.xls',C{1},N)
end

3 Comments

It works partially. here is what i edited
sheetname='page';
for k = 1:60
F = sprintf('Data_%d.mat',k);
P = fullfile('matfiles',F);
S = load(F);
C = struct2cell(S);
xlwrite('saved_file.xls',C{1},sheetname,'B2')
but the rows are not updated. Picture how a spreadsheet looks like.so i have only one row filled out i.e the last iteration. is there a way to make the row update as well? for example 'B2' becomes 'B3' in the second itereration and so on. so that the Data_2 fills in that row. and so on.
"is there a way to make the row update as well?"
Of course, just use sprintf to specify the address:
pos = sprintf('B%d',1+k);
xlwrite('saved_file.xls',C{1},sheetname,pos)

Thank man! remind me to buy u chocolate xD

Sign in to comment.

Products

Asked:

on 19 Oct 2018

Edited:

on 19 Oct 2018

Community Treasure Hunt

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

Start Hunting!