Filter löschen
Filter löschen

how to use a for cycle with strings as variables

1 Ansicht (letzte 30 Tage)
Hugo
Hugo am 25 Feb. 2022
Kommentiert: Stephen23 am 25 Feb. 2022
Hello,
I would like to write 10 variables at once in separate files. Is there a way to make my code more efficient? I am thinking of using a "for" cycle, but I can't do it in this case.
writematrix(data1, "data1.txt");
writematrix(data2, "data2.txt");
writematrix(data3, "data3.txt");
writematrix(data4, "data4.txt");
writematrix(data5, "data5.txt");
writematrix(data6, "data6.txt");
writematrix(data7, "data7.txt");
writematrix(data8, "data8.txt");
writematrix(data9, "data9.txt");
writematrix(data10, "data10.txt");
I thank you in advance,
Best regards,
  1 Kommentar
Stephen23
Stephen23 am 25 Feb. 2022
"Is there a way to make my code more efficient?"
Avoid numbered variable names.
Use indexing in a loop.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 25 Feb. 2022
As soon as you do not hide indices in the names of variables, but use arrays instead, the code is trivial:
for k = 1:10
writematrix(data{k}, sprintf('data%i.txt', k));
end
By the way, prefer to include leading zweos for the numbering of the files:
sprintf('data%03i.txt', k)
Then the alphabetical order is the numerical order also.

Weitere Antworten (0)

Tags

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by