Trying to optimise this loop

11 visualizzazioni (ultimi 30 giorni)
James
James il 26 Gen 2024
Commentato: Shadow il 3 Apr 2024 alle 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

Risposte (2)

Bruno Luong
Bruno Luong il 26 Gen 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 il 3 Apr 2024 alle 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 Commento
Shadow
Shadow il 3 Apr 2024 alle 12:17
Test with
WriteOutValuesToAFile("test.txt",rand(2,2,9)); type test.txt

Accedi per commentare.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by