How to print 1x50 array into a text file

조회 수: 30 (최근 30일)
Iman Baz
Iman Baz 2019년 5월 23일
댓글: Akira Agata 2019년 5월 23일
Hello,
I have 1x50 array A=[0.020 0.600 49.915 0.000 0.100 0.000 30.910 51.340 30.850 .... 0.000]
and want to print them into a text file with the below format.
0.020 0.600 49.915 0.000 0.100 0.000 30.910 51.340
30.850 51.460 13.378 4.600 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000
How should I do this?
  댓글 수: 1
Jan
Jan 2019년 5월 23일
편집: Jan 2019년 5월 23일
And what exactly is the "below format"? Do you want spaces or tab stops between the numbers? Tab stops before the line breaks? A fixed number of 8 columns, or does this depend on the number of elements? A trailing linebreak or not? 10 characters per number and 3 digits after the point? Please mention the details.

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

채택된 답변

Jan
Jan 2019년 5월 23일
Maybe:
[fid, msg] = fopen(FileName, 'w');
assert(fid ~= -1, 'Cannot open file for writing: %s\n%s\n', FileName, msg);
fmt = [repmat('%10.3f', 1, 8), '\n'];
fprintf(fid, fmt, A.');
fclose(fid);

추가 답변 (2개)

Akira Agata
Akira Agata 2019년 5월 23일
How about the following?
dlmwrite('output.txt',reshape(A(1:48),8,6)','delimiter','\t');
dlmwrite('output.txt',A(49:50),'-append','delimiter','\t');
  댓글 수: 2
Iman Baz
Iman Baz 2019년 5월 23일
Dear Agata,
Thank you for your prompt reply. that's worked.
but I need numbers in format %10.3f.
Akira Agata
Akira Agata 2019년 5월 23일
Dear Hossein-san,
Thank you for your comment.
Sorry, I've missed your 'fprintf' tag in your original post.
Just FYI, your can save as %10.3f format by dlmwrite function, too, by:
dlmwrite('output.txt',reshape(A(1:48),8,6)','delimiter','\t','precision','%10.3f');
dlmwrite('output.txt',A(49:50),'-append','delimiter','\t','precision','%10.3f');

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


Raj
Raj 2019년 5월 23일
편집: Raj 2019년 5월 23일
Answer given by Akira is the optimal solution but since you have mentioned 'fprintf' as a tag, here are two ways to get what you want using 'fprintf'
fid=fopen('MyFile.txt','w'); % Open text file
fprintf(fid, '%10.3f %10.3f %10.3f %10.3f %10.3f %10.3f %10.3f %10.3f\r\n',A); % Write 8 elements in each line from A with 3 digits after decimal
fclose(fid); % Close the file
or an even weird way:
fid=fopen('MyFile.txt','w');
for i=1:numel(A)
if rem(i,8)~=0
fprintf(fid, ' %10.3f',A(1,i));
else
fprintf(fid, ' %10.3f\r\n',A(1,i));
end
end
fclose(fid);
Good luck!!

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by