How to apply fprinf for matrix

조회 수: 2 (최근 30일)
Ali
Ali 2016년 5월 27일
댓글: Ali 2016년 5월 27일
I would like to use fprintf for Writing data to a text file. I want to apply fprintf on the following matrix. I have a matrix with n rows and 3 columns. please help with this issue. thanks a lot. for instance.
0.0000 0.0000 0.0000
0.0000 0.1000 0.0000
0.0643 0.0675 0.0000
0.1000 0.0000 0.0000
0.0000 0.2000 0.0000
0.2000 0.0000 0.0000
0.0725 0.1500 0.0000
0.1488 0.0873 0.0000
0.0726 0.2501 0.0000
0.0000 0.3000 0.0000
0.0000 0.4000 0.0000
0.3000 0.0000 0.0000
0.4000 0.0000 0.0000
  댓글 수: 1
Stephen23
Stephen23 2016년 5월 27일
편집: Stephen23 2016년 5월 27일
Don't use a loop! See my answer to know how.

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

채택된 답변

Stephen23
Stephen23 2016년 5월 27일
편집: Stephen23 2016년 5월 27일
This is MATLAB, so there really is no point in using an ugly loop when you can do it much faster and simpler with just one csvwrite call:
csvwrite('test.csv',M)
or with one fprintf call (no loop is required!):
M = [...
0.0000,0.0000,0.0000;...
0.0000,0.1000,0.0000;...
0.0643,0.0675,0.0000;...
0.1000,0.0000,0.0000;...
0.0000,0.2000,0.0000;...
0.2000,0.0000,0.0000;...
0.0725,0.1500,0.0000;...
0.1488,0.0873,0.0000;...
0.0726,0.2501,0.0000;...
0.0000,0.3000,0.0000;...
0.0000,0.4000,0.0000;...
0.3000,0.0000,0.0000;...
0.4000,0.0000,0.0000];
%
fid = fopen('test.csv','wt');
fprintf(fid,'%f,%f,%f\n',M.')
fclose(fid);
  댓글 수: 1
Ali
Ali 2016년 5월 27일
Thanks a lot for helping me to solve this issue.

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

추가 답변 (3개)

Stalin Samuel
Stalin Samuel 2016년 5월 27일
%example code
s = rand(10,3);
fileID = fopen('a.txt','w');
for i=1:length(s)
fprintf(fileID,'%g\t%g\t%g \r\n',s(i,:));
end
fclose(fileID);
  댓글 수: 1
Ali
Ali 2016년 5월 27일
Many thanks for your help.

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


TastyPastry
TastyPastry 2016년 5월 27일
fh = fopen('newFile.txt','w');
for i=1:size(myData,1)
fprintf(fh,'%d %d %d\n',a(i,1),a(i,2),a(i,3))
end
  댓글 수: 1
Ali
Ali 2016년 5월 27일
Thanks a lot for your code.

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


Guillaume
Guillaume 2016년 5월 27일
Why not simply use dlmwrite?
dlmwrite('test.csv', M, 'delimiter', ' ');
or if you want to specify the precision
dlmwrite('test.csv', M, 'delimiter', ' ', 'precision', '%6.4f');
  댓글 수: 1
Ali
Ali 2016년 5월 27일
Thank you very much Guillaume.

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

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by