Effacer les filtres
Effacer les filtres

Trying to optimise this loop

1 vue (au cours des 30 derniers jours)
James
James le 26 Jan 2024
Commenté : Shadow le 3 Avr 2024
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

Réponses (2)

Bruno Luong
Bruno Luong le 26 Jan 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 le 3 Avr 2024
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 commentaire
Shadow
Shadow le 3 Avr 2024
Test with
WriteOutValuesToAFile("test.txt",rand(2,2,9)); type test.txt

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by