Borrar filtros
Borrar filtros

how to use a for cycle with strings as variables

1 visualización (últimos 30 días)
Hugo
Hugo el 25 de Feb. de 2022
Comentada: Stephen23 el 25 de Feb. de 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 comentario
Stephen23
Stephen23 el 25 de Feb. de 2022
"Is there a way to make my code more efficient?"
Avoid numbered variable names.
Use indexing in a loop.

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 25 de Feb. de 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.

Más respuestas (0)

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by