Matlab shows results as a formula when i need a numeric value
1 次查看(过去 30 天)
显示 更早的评论
I am trying to write modified newton formula in matlab, but the matlab shows results x form, not numeric. here is the code.
clc
format long g
syms x;
fun = input ('Enter the function f(x)= : ');
f=inline(fun);
z=diff(f(x));
f1=inline(z);
z1=diff(f1(x));
f2=inline(z1);
u1=[f(x)/f1(x)];
u2={1-[(f(x)*f2(x))/(f1(x)^2)]};
x0=input('enter the first guess x0=: ');
for i=0:6
xn=x;
x=xn-[u1/u2];
end
i
and the results are,
I am trying to write modified newton formula in matlab, but the matlab shows results x form, not numeric. here is the code.
clc format long g syms x; fun = input ('Enter the function f(x)= : ','s'); f=inline(fun); z=diff(f(x)); f1=inline(z); z1=diff(f1(x)); f2=inline(z1); u1=f(x)/f1(x); u2=1-[(f(x)*f2(x))/(f1(x)^2)]; x0=input('enter the first guess x0=: '); for i=0:6 xn=x x=xn-[u1/u2]; if x==xn break end end and here are the results;
Enter the function f(x)= : x^2-2 enter the first guess x0=: 1
xn = x
xn = x + (x^2 - 2)/(2*x*((2*x^2 - 4)/(4*x^2) - 1))
xn = x + (x^2 - 2)/(x*((2*x^2 - 4)/(4*x^2) - 1))
xn = x + (3*(x^2 - 2))/(2*x*((2*x^2 - 4)/(4*x^2) - 1))
xn = x + (2*(x^2 - 2))/(x*((2*x^2 - 4)/(4*x^2) - 1))
xn = x + (5*(x^2 - 2))/(2*x*((2*x^2 - 4)/(4*x^2) - 1))
xn = x + (3*(x^2 - 2))/(x*((2*x^2 - 4)/(4*x^2) - 1))
how can i fix that? thanks.
0 个评论
回答(1 个)
Christiaan
2015-3-9
编辑:Christiaan
2015-3-9
Dear Hakan,
The Funktion inline will be removed in a future release of Matlab Inline (Mathworks) . Therefore an another way to use the newthon ralphson technique is by this code:
clc;clear all;close all; syms x; fun = input ('Enter the function f(x)= : ','s'); fun = sym(fun); derfun = diff(fun,x); x0=input('enter the first guess x0=: ');
for i=1:10 if i==1 x_old = x0; else x_old = x_new; end
fx_old = subs(fun,x,x_old);
dfdx_old = subs(derfun,x,x_old);
x_new = x_old-(fx_old/dfdx_old)
x_new = vpa(x_new,6) ;
if x_old==x_new
break
end
end
Good Luck! Christiaan
2 个评论
Christiaan
2015-3-11
Hello Hakan,
I modified the code for you:
clc;clear all;close all;
syms x;
fun = input ('Enter the function f(x)= : ','s');
fun = sym(fun);
derfun = diff(fun,x);
derfun2 = diff(derfun,x);
x0=input('enter the first guess x0=: ');
for i=1:30
if i==1
x_old = x0;
else
x_old = x_new;
end
fx_old = subs(fun,x,x_old);
dfdx_old = subs(derfun,x,x_old);
d2fdx2_old = subs(derfun2,x,x_old);
u_1 = fx_old/dfdx_old;
u_2 = 1-(fx_old*d2fdx2_old)/(dfdx_old*dfdx_old);
x_new = x_old-(u_1/u_2)
x_new = vpa(x_new,6) ;
if x_old==x_new
break
end
end
Kind regards, Christiaan
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!