필터 지우기
필터 지우기

Trying to optimise this loop

조회 수: 1 (최근 30일)
James
James 2024년 1월 26일
댓글: Shadow 2024년 4월 3일
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

답변 (2개)

Bruno Luong
Bruno Luong 2024년 1월 26일
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 2024년 4월 3일
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
Shadow
Shadow 2024년 4월 3일
Test with
WriteOutValuesToAFile("test.txt",rand(2,2,9)); type test.txt

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by