Trying to optimise this loop
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Low-Level File I/O 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!