Newton method root finding: School project help.
Afficher commentaires plus anciens
Hello, I am working on a project for school, that requires I use a newton root finding method. While trying to write the code for this, I keep getting the error shown below. Any suggestions? The code, and error are below.Thanks in advance.
Code:
function [root,ea,iter]=newtraph(func,dfunc,xr,es,maxit,varargin)
if nargin<3,error('at least 3 input arguments required'),end
if nargin<4|isempty(es),es=0.0001;end
if nargin<5|isempty(maxit),maxit=50;end
iter = 0;
while (1)
xrold = xr;
xr = xr - func(xr)/dfunc(xr);
iter = iter + 1;
if xr ~= 0, ea = abs((xr - xrold)/xr) * 100; end
if ea <= es | iter >= maxit, break, end
end
root = xr;
When I try to use the function, I get the following error message:
>> newtraph(func,dfunc,xr,1.0E-12)
??? Attempted to access func(1.21526); index must be a positive integer or logical.
Error in ==> newtraph at 22
xr = xr - func(xr)/dfunc(xr);
2 commentaires
Eric
le 10 Mar 2015
First, thanks for asking for help in an appropriate fashion. You were honest that this is an assignment for a class and provided your initial attempt. That's surprisingly rare. All too often people post questions that are obviously homework assignments in the hopes they'll get the community to do it for them.
The use of function handles as described by John D'Errico below is the answer you're looking for, I believe. I thought I'd also chime in and mention that you might look at the documentation for the inputParser object. It lets you handle optional inputs and named parameters elegantly. Alternatively you might look at the documentation for narginchk and nargoutchk. Your code currently checks the minimum number of inputs but not the maximum (indeed, 6 or more inputs are allowed because you use varargin but these extra inputs would not be used for anything).
-Eric
Daniel Platt
le 10 Mar 2015
Réponse acceptée
Plus de réponses (1)
Image Analyst
le 10 Mar 2015
How did you define func? It thinks it's an array and that you're trying to access the 1.21526'th element of it, which of course there is no such element. Maybe if func is a function you need to call it like this:
newtraph(@func,dfunc,xr,1.0E-12)
1 commentaire
Daniel Platt
le 10 Mar 2015
Catégories
En savoir plus sur Data Type Identification dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!