Matlab Query

neilofbodom

Member
Hi guys

I'm implementing the Newton-Raphson method in Matlab. It works fine, but the only problem is that the values are being printed as fractions and not as decimals. I tried using format long but absolutely nothing happened.

My code:

syms x
f(x) = (x^2) - 40;
df = diff(f,x);
x(1) = 6;

for i = 1:10
format long;
x(i+1) = x(i)-(f(x(i))/df(x(i)));
disp(' Iterate ');
disp(i);
disp(' X ');
disp(x(i));
end


Any ideas?


Cheers
 
@Cromewell

I've just tagged another admin to help you with this since he knows programming pretty well. Not sure when he'll log on though, may be a day or so.
 
Sorry I don't have matlab to test with, the typing seems to be C like, except on output formatting... From the docs I'd guess you want
Code:
format long e;
 
Nope, tried it on Matlab R2015a, this is what you get (a portion of it):

Iterate
2

X
19/3

I think you need to replace your Disp commands with Fprintf. That way you can specify you want decimals:

Code:
syms x
f(x) = (x^2) - 40;
df = diff(f,x);
x(1) = 6;

for i = 1:10
format long e;
x(i+1) = x(i)-(f(x(i))/df(x(i)));
fprintf('%s',' Iterate ');
fprintf('%i',i);
fprintf('%s',' X ');
fprintf('%e','x(i)');
end

Here you can find some help on fprintf: http://fr.mathworks.com/help/matlab/ref/fprintf.html
 
Back
Top