How to run this code on any inputs?Newton

function [p,k] = newton(f,df,p0,tol)
for k=1:100
p = p0 - f(p0)/df(p0);
if abs(p-p0)<tol, break; end
p0 = p;
end
I have that but where do I put the tolerance, the function and everything else for it to run. I'm really new at all this.

댓글 수: 4

Geoff Hayes
Geoff Hayes 2014년 9월 21일
cakey - presumably f and df are function handles and your code makes use of the function f and its derivative df. Also since you are using the tolerance tol as a condition to break out of the loop and the initial point p0, it isn't clear to me what you mean by where do I put the tolerance, the function and everything else for it to run. Please clarify what it is that you need help with.
cakey
cakey 2014년 9월 22일
편집: Matt J 2014년 9월 22일
My teacher helped me he said I needed to do this:
f=@(x) (x.^3+x+2);
df=@(x)(3*x.^2+1);
p0=1;
tol=10^-3;
[p, k] = newton(f,df,p0,tol);
disp([p,k]);
cakey
cakey 2014년 9월 22일
Can you help me understand why I need to do this function handle business? Why do I also need to hit disp? I'm completely new to this all.
Stephen23
Stephen23 2014년 9월 22일
Read about function handles, it might help. And use the contents browser, which is on the left-hand side of the help window, to discover related topics... it really is very handy!

댓글을 달려면 로그인하십시오.

 채택된 답변

Matt J
Matt J 2014년 9월 22일
편집: Matt J 2014년 9월 22일

0 개 추천

When you encounter commands or expressions that you don't understand, you should be reading their documentation pages to see what they do,
>> doc disp
>> docsearch 'function handle'
Even more importantly, you should be playing with these commands individually at the command line to test your understanding of the documentation. It should have been very easy for you to discover that disp() is a way to display results in the command window just by trying it,
>> disp([1,2])
1 2
>> disp([3,4,5])
3 4 5
It should have been similarly easy to learn that constructing function handles like
f=@(x) (x.^3+x+2);
allow your newton routine to evaluate your f(x) at different points, as the algorithm requires:
>> f(0)
ans =
2
>> f(1)
ans =
4

추가 답변 (1개)

Stephen23
Stephen23 2014년 9월 22일

1 개 추천

What you have is a function, which can be run to create some outputs. It could be good to revise MATLAB's comprehensive help on calling functions . If you are learning MATLAB, you will have to get used to doing a lot of reading of help pages. But don't worry, MATLAB's help pages are really quite good, with plenty of examples to try, and explanations of concepts that you need to understand. You should learn to navigate using the help contents browser too. Good luck!

카테고리

도움말 센터File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품

질문:

2014년 9월 21일

댓글:

2014년 9월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by