fprintf not writing same information from command window

I want to create two columns. The first column has numbers 1 through 10 from f. The second column has zeros from b, but in certain positions contained in a there needs to be values. Some of the values are duplicates so that is taken care of with the accumarray. I need the zeros to be in the format 0.0 and the numbers have 9 decimal places. When I type out in the command window it had the correct numbers in the correct places but the zeros and number formats are incorrect, but in the xlsreadtrial.txt file it doesn't look correct.
b=zeros(10,1);
% writes zeros
a = xlsread('trial.xlsx','Sheet2','A1:B4');
% reads values from excel
f = (1:1:10)';
% first column values
h=a(:,1);
% breaks a into first column only
n=a(:,2);
% breaks a into second column only
k=[f;h];
% adds first column of a onto the end of f
m=[b;n];
% adds second column of a onto the end of b
p=[k,m];
% combines first and second columns
c = 9 * ones(length(p),1);
c(b==0) = 1;
out=[unique(p(:,1)) accumarray(p(:,1),p(:,2))];
% makes first column values unique and accounts for duplicates
fileID = fopen('xlsreadtrial.txt','w');
fprintf(fileID,'%d,%.f\n',out');
fclose(fileID);

댓글 수: 4

Hi,
To display more number of decimal places, you may try using ' format '.
>> format long
For your .txt file, the following code modification worked for me.
>> fprintf(fileID,'%d,%d\n',out');
Note: I am using R2018a MATLAB.
Jan
Jan 2018년 6월 14일
편집: Jan 2018년 6월 14일
I don't get it. Do you mean the number format or the values? This would be clear if you provide some input data, which reproduce the problem and you post the output you get and the one you want.
Screenshots are not a good choice here, because it is not clear, what has been cropped.
Maybe all you need is:
fprintf(fileID,'%d,%g\n', out');
or
fprintf(fileID,'%d,%.4g\n', out');
%g now displays the correct numbers in the txt file output but I want to have a variable number of decimal places so the output looks like this:
1,0.368945
2,0.0
3,0.598765
4,0.0
5,0.500000
6,0.0
7,0.0
8,0.0
9,0.0
10,0.0

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

답변 (1개)

Jonathon Gibson
Jonathon Gibson 2018년 6월 14일
편집: Jonathon Gibson 2018년 6월 14일
If you want different formatting depending on the row, you can print each row individually:
fileID = fopen('xlsreadtrial.txt','w');
for row = out'
if row(2) == 0
fprintf(fileID,'%d,%.1f\n',row);
else
fprintf(fileID,'%d,%.9f\n',row);
end
end
fclose(fileID);
Which gives you 9 decimal places if the second column is not equal to 0 and just 1 decimal place for the 0s.
1,0.368945000
2,0.0
3,0.598764523
4,0.0
5,0.500000000
6,0.0
7,0.0
8,0.0
9,0.0
10,0.0

카테고리

도움말 센터File Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

제품

릴리스

R2018a

질문:

2018년 6월 14일

편집:

2018년 6월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by