필터 지우기
필터 지우기

fprintf varying number of decimal places in a column

조회 수: 7 (최근 30일)
Anna Cole
Anna Cole 2018년 6월 4일
답변: Walter Roberson 2018년 6월 4일
I have a column with mostly zeros and a few numbers. On the zero values I need them to display as 0.0 and the number values I need to display the actual number of decimals such as 1.23456789. What formatting can I use?
  댓글 수: 7
Anna Cole
Anna Cole 2018년 6월 4일
I tried the %.*f earlier and this was the result
dpb
dpb 2018년 6월 4일
You used the '*' in the format string but didn't pass a corresponding vector of values to fill the place holder so fprintf used the next data from d when needed, leaving shorthanded as far as actual data to print.

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

채택된 답변

Walter Roberson
Walter Roberson 2018년 6월 4일
b=zeros(10,1);
b(5)=4.56987;
b(6)=6.4;
a=[1:1:10]';
c = 5 * ones(length(a),1);
c(b==0) = 1;
d=[a,c,b];
fileID = fopen('fprintftrial.txt','w');
fprintf(fileID, '%d,%.*f\n', d');
fclose(fileID);
Result looks like
1,0.0
2,0.0
3,0.0
4,0.0
5,4.56987
6,6.40000
7,0.0
8,0.0
9,0.0
10,0.0

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by