필터 지우기
필터 지우기

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 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