Export multiple tables in loop

조회 수: 9 (최근 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