Export multiple tables in loop

6 次查看(过去 30 天)
Rasmus Harbo
Rasmus Harbo 2020-2-11
评论: Stephen23 2020-2-11
Hi
I have 10+ tables that i want to export to excel using a loop to be efficient. I just can seem to figure out how to loop through the variables
My variables are called f5_1 to _10 and f5r_1 to _10 here is an example of what i am trying to do
for i = 1:10
writetable(f5_i, 'FF5_results.xlsx','Sheet',i)
writematrix(f5r_i, 'FF5_results.xlsx','Sheet',i,'Range','A9')
end
Any help is much appreciated
thanks in advance
  1 个评论
Stephen23
Stephen23 2020-2-11
"I have 10+ tables that i want to export to excel using a loop to be efficient."
Of course, this is very easy and very efficient using indexing. So you just need your tables in one cell array or something similar, and then you can do this so easily.... what could the problem be?
"My variables are called f5_1 to _10 and f5r_1 to 10"
Ah, so that is the problem: you forced meta-data into variable names. Forcing meta-data into variable names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
You would be much better off redesigning your data so that it does not include meta-data in the variable names.
Why are you not storing this data in one table?

请先登录,再进行评论。

回答(1 个)

Bhaskar R
Bhaskar R 2020-2-11
Usually you should do as
var_name = ['f5_', str2num(i)];
writetable(eval(var_name), 'FF5_results.xlsx','Sheet',i);
But Variable evaluation is not recommended, try to put your data () in cell array as
f5 = cell(1, 10); % assign 1 to 10 cell with your data
f5r = cell(1, 10); % assign 1 to 10 cell with your data
Then run
for i = 1:10
writetable(f5{i}, 'FF5_results.xlsx','Sheet',i)
writematrix(f5r{i}, 'FF5_results.xlsx','Sheet',i,'Range','A9')
end

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by