newton method code with user input
조회 수: 2 (최근 30일)
이전 댓글 표시
HI, I have simple problem, Iam trying to use newton's method with the code below. However since my polynomial is always going to be in fourth order I wish to make it a user input method to make it easier for myself rather than having to write the 100+ polynomials.
% code
function p=test(x)
a1=input('Type a1 value: \n');
a2=input('Type a2 value: \n');
a3=input('Type a3 value: \n');
a4=input('Type a4 value: \n');
p=1+a1*x+a2*x^2+a3*x^3+a4*x^4;
z=diff(f(x));
f1=inline(z);
x0=input('Guess the number= \n');
x=x0
for u=0:inf
y=x
x=y-(f(x)/f1(x));
if x==y
break
end
end
I will greatly appreciate your help.
thanks
댓글 수: 1
Ced
2016년 3월 6일
편집: Ced
2016년 3월 6일
I am not sure I understand the question. Why would you have to write 100+ polynomials? Why not just pass the coefficients as a input parameter to your function, i.e.
function p = test(x,a)
% a = [ a0 a1 a2 a3 a4 ]
p = x.^(0:5)*a(:); % this does 1*a0 + x*a1 + ... + x^4*a4
...
Otherwise, you can also pass a complete vector with input:
a = input('Type the coefficient vector [ a0 a1 a2 a3 a4 ]\n');
Then, minor comments:
1. I would recommend using a finite maximum number of iterations instead of inf.
2. You will probably want to check (abs(x-y) < small_number) instead of x == y since this is a numerical algorithm.
PS: You might want to have a look at polyval if you want to use inbuilt matlab functions with polynomials
답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Polynomials에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!