What is wrong with my fprintf?

I am trying to print out the value of y to be 6 decimals, if I type it as format long or short it pops out those lengths. I am trying to make as many decimals places as D, but the default is 6 if not declared.
function y=atan_approx(x,D)
y=0;
n=1;
k=1;
if nargin==1,D=6,disp('Value of D was set to 6'), end
while n<100
y=y+(x.^n./n).*k;
n=n+2;
k=k*-1;
end
fprintf('The value of the approximation is %10.Df\n',y)
z=-1:0.01:1;
plot(z, atan(z),'--g')
hold
plot(x,y,'ro')
end
>>format long
>>atan_approx(0.5,7)
The value of the approximation is current plot held
ans =
0.4636476090086
if i make it format short the ans is 0.4636

回答 (2 件)

Walter Roberson
Walter Roberson 2017 年 2 月 5 日

0 投票

fprintf('The value of the approximation is %10.6f\n',y)
Your %10.Df uses an invalid format specifier, 'D', so that ends printing out on that line. Then the "current plot held" is coming from the "hold" command you have.
per isakson
per isakson 2017 年 2 月 6 日
編集済み: per isakson 2017 年 2 月 6 日

0 投票

"What is wrong with my fprintf?" &nbsp I assume that you intend to control the number of decimals places with the variable D. Here are two format specifiers, which do that. (Look up the help on fprintf. )
>> cssm( pi, 5 )
The value of the approximation is 3.14159
Or with a parameterized specifier 3.14159
>>
where
function cssm( y, D )
frmt = sprintf( 'The value of the approximation is %%10.%df\n', D );
fprintf( frmt, y );
fprintf( 'Or with a parameterized specifier %10.*f\n', D, y );
end

カテゴリ

ヘルプ センター および File ExchangeEntering Commands についてさらに検索

質問済み:

2017 年 2 月 5 日

編集済み:

2017 年 2 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by