how to use a for cycle with strings as variables

1 回表示 (過去 30 日間)
Hugo
Hugo 2022 年 2 月 25 日
コメント済み: Stephen23 2022 年 2 月 25 日
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 Center および File ExchangeWhos についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by