Can I combine character data and numerical data in a fprintf statement

Hi I have found what I think is a bug. When I try writing to a text file, the %f format is not being correctly interpreted.
Date=str2mat('1889-01-01','1889-01-02','1889-01-03');
Data=[ 2.4000 7.2511 25.5000 40.5000 24.0000 0.3254 1.7000;
4.7000 7.4953 26.0000 41.0000 25.0000 0.3165 1.7000;
0.3000 7.4547 25.0000 41.5000 25.0000 0.3184 1.7000];
fprintf(1,'%c%c%c%c%c%c%c%c%c%c,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f\n',[Date,Data]');
Yields:
1889-01-01, 2.00, 7.00,25.00,40.00,24.00, 0.00, 1.00;
1889-01-02, 4.00, 7.00,26.00,41.00,25.00, 0.00, 1.00;
1889-01-03, 0.00, 7.00,25.00,41.00,25.00, 0.00, 1.00
Note the numerical data are not getting any precision after the decimal point.

Answers (2)

Yes, that is a bit strange. I made a little experiment:
>> fprintf( 1, '%c,%7.3f\n', [ 122, pi, 122, pi ] )
z, 3.142
z, 3.142
and
>> fprintf( 1, '%c,%7.3f\n', [ 'z', pi, 'z', pi ] )
z, 3.000
z, 3.000
.
concatenating < char> and < double> seems to be the problematic part.
>> [ 'z', pi, 'z', pi ]
ans =
zz
>> class( [ 'z', pi, 'z', pi ] )
ans =
char
.
Whether this is a bug or not depends on what the documentation says.
One more test:
>> fprintf( 1, '%c,%7.3f\n', [ 'z', 20*pi, 'z', 20*pi ] )
z, 62.000
z, 62.000
>> fprintf( 1, '%c,%7.3f\n', [ 'AZ'] )
A, 90.000
and
>> cast( cast( 20*pi, 'char' ), 'double' )
ans =
62
.
My guess is that this is documented behavior of concatenating < char> and < double>.
The Matlab documentation says:
Combining character values with double values yields a character matrix. MATLAB converts the double elements in this example to their character equivalents
To get the desired output, you have to use something like this
for i = 1:size(Date, 1)
fprintf('%s ', Date(i,:))
fprintf('%5.2f ', Data(1,:))
fprintf('\n')
end
or this
for i = 1:size(Date, 1), disp([Date(i,:) ' ' num2str(Data(1,:), '%5.2f ')]), end

Categories

Products

Asked:

on 7 Feb 2013

Community Treasure Hunt

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

Start Hunting!