Trying to optimise this loop

11 visualizaciones (últimos 30 días)
James
James el 26 de En. de 2024
Comentada: Shadow el 3 de Abr. de 2024 a las 12:17
Hello,
I'm new to Matlab, and trying to write code that talks a 3-D array, and writes a csv file with the first two dimensions of one line, then repeated for each z entry. For instance an array of size 6,6,5 would output 36 values over 5 lines. The horrible code I wrote to do this is, how would I do this properly?
Thanks
James
function WriteOutValuesToAFile(filename,M)
fileID = fopen(filename,'w');
for k=1:size(M,3);
arr=M(:,1,k);
fprintf(fileID, "%f",arr(1));
for i=2:size(M,1);
fprintf(fileID,",%f",arr(i));
end
for j=2:size(M,2);
arr=M(:,j,k);
for i=1:size(M,1);
fprintf(fileID,",%f",arr(i));
end
end
fprintf(fileID, "\n");
end
fclose(fileID);
end

Respuestas (2)

Bruno Luong
Bruno Luong el 26 de En. de 2024
function WriteOutValuesToAFile(filename,M)
fileID = fopen(filename,'wt');
for k=1:size(M,3);
s = sprintf('%f,', M(:,:,k));
s(end) = [];
fprintf(fileID, "%s\n", s);
end
fclose(fileID);
end

Shadow
Shadow el 3 de Abr. de 2024 a las 12:16
function WriteOutValuesToAFile(filename,M)
text = "";
for c = 1:size(M,3)
text = text + mat2str(M(:,:,c)) + newline;
end
writelines(text,filename,Writemode="append",Encoding="UTF-8")
end
  1 comentario
Shadow
Shadow el 3 de Abr. de 2024 a las 12:17
Test with
WriteOutValuesToAFile("test.txt",rand(2,2,9)); type test.txt

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by