Why is one variable not printing to my text correctly?

조회 수: 4 (최근 30일)
Alex
Alex 2017년 3월 18일
댓글: Alex 2017년 3월 18일
I use the following code, but when I open changing.txt, it shows:
547.0 0.0000 547.0 360.0 iri_pd_lon280.txt
The second variable '0.0000' should be '0.3720'.
calc_alt=547.5000;
calc_W=0.3720;
alt_Bw=547.5000;
alt_nm=360;
filenames='iri_pd_lon280.txt';
fmt='%8.1f %.4f %8.1f %8.1f %s\r\n';%format for fprint
fileID=fopen('changing.txt','a');
fprintf(fileID,fmt, [calc_alt calc_W alt_Bw alt_nm filenames]);%write these values at the end of the file
fclose (fileID);

채택된 답변

dpb
dpb 2017년 3월 18일
Bad syntax... [calc_alt calc_W alt_Bw alt_nm filenames] you're concatenating unlike variables and passing that to fprintf
Lose the braces, use a list of arguments instead--
fprintf(fileID,fmt, calc_alt, calc_W, alt_Bw, alt_nm, filenames)
and nirvana will ensue...
BTW, there's a repmat "trick" for writing format strings that's very handy to have seen--
fmt=[repmat(['%8.1f %.4f' repmat('%8.1f,1,2) '%s\n'];
not that bad here, but when numbers get to be much larger it can be a real boon...
BTW2: '\n' is enough on its own in virtually every case any more; adding both slows things down for no real benefit in general.

추가 답변 (0개)

카테고리

Help CenterFile 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!

Translated by