how to use a for cycle with strings as variables

3 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2022-2-25
"Is there a way to make my code more efficient?"
Avoid numbered variable names.
Use indexing in a loop.

请先登录,再进行评论。

采纳的回答

Jan
Jan 2022-2-25
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.

更多回答(0 个)

类别

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

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by