File name as value of a variable

Would you please guide me how to write Excel files whose names are value of a variable, e.g. testdata_i where i is a variable?
This is the code I have that needs some adjustments. Data is a matrix whose values is decided in another loop.
for i = 1:5
filename = sprintf('%s_%d','testdata',i)
writematrix(Data,'filename.xlsx')
end

 Respuesta aceptada

Adam Danz
Adam Danz el 24 de Jun. de 2019
Editada: Adam Danz el 24 de Jun. de 2019
You were really close. You just forgot to use the filename variable.
for i=1:5
filename = sprintf('testdata_%d.xlsx',i);
writematrix(Data,filename)
end
I recommend using absolute paths that specify where the file will be stored by using fullfile()
d = 'C:\Users\name\Documents\MATLAB';
for i=1:5
filename = sprintf('testdata_%d.xlsx',i);
writematrix(Data,fullfile(d,filename))
end

2 comentarios

madhan ravi
madhan ravi el 24 de Jun. de 2019
+1, SHAWN this answer , answered your question already. Had the same thing in mind but messsed up my answer.
Shawn
Shawn el 24 de Jun. de 2019
It's working like a charm!
Thank you Adam and Madhan for your quick responses.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Interactive Control and Callbacks en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 24 de Jun. de 2019

Editada:

el 14 de Feb. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by