Export multiple tables in loop

10 vues (au cours des 30 derniers jours)
Rasmus Harbo
Rasmus Harbo le 11 Fév 2020
Commenté : Stephen23 le 11 Fév 2020
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 commentaire
Stephen23
Stephen23 le 11 Fév 2020
"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?

Connectez-vous pour commenter.

Réponses (1)

Bhaskar R
Bhaskar R le 11 Fév 2020
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

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by