|
"Rune Allnor" <allnor@tele.ntnu.no> wrote in message
news:71b32cd3-6262-4502-a5ea-edc138e5b6a6@f11g2000yql.googlegroups.com...
> On 11 Des, 14:34, "Chm " <lrh...@gmail.com> wrote:
>> So I'm writing this code to find the root of a function. It works fine
>> with some functions. However, whenever I try to solve cos(x) it returns a
>> value where cos(x)=1 instead of 0. Can somebody help me figure out what
>> the problem is? thank you!
>
>> function root = newton(g,cc,x0)
>
> You need a function for the gradient as well.
>
>> d_f = inline(char(diff(g)));
>
> I don't like this line. First of all, you can not
> use the Newton iteration with a fixed data vector.
> The data points are computed along the way.
>
> Second, you need a function to compute the gradient.
> It is supplied either as a separate function,
> or you need to somehow use g to compute the gradient
> around a test point x.
>
> Third, I don't understand what the CHAR function
> has to do in here.
The OP has Symbolic Math Toolbox installed, and they realized that this:
root = newton('sin(x)', ...)
would work. The reason it works is (deep breath) that line will create an
inline function object from the string created by converting the symbolic
result of differentiating the function represented by the input string. So
the OP is using a function, albeit one they went a somewhat roundabout way
to create.
FYI for the OP: the Symbolic Math Toolbox version of DIFF for char arrays is
being removed; in future versions this code will go through the MATLAB
implementation of DIFF for char arrays, which will NOT treat the char array
as a function but as a regular old array of characters. When that happens,
diff('sin(x)') will return diff(double('sin(x)'));
http://www.mathworks.com/help/toolbox/symbolic/rn/bsllh45-1.html#bsllmg2-1
Instead, I recommend using function handles:
root = newton(@sin, ...)
and either passing a function handle that you can evaluate to determine the
derivative into newton as an additional input argument or approximating it
using finite differences.
http://en.wikipedia.org/wiki/Finite_difference_method
Of course, if you're not doing this for a class you could always use FZERO.
> Maybe you mess around with symbolic fundtions.
> If so,you should be aware that the Newton-Raphson
> method works with numerical functions.
Even though it doesn't look like it, the OP is using functionality from
Symbolic Math Toolbox.
--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com
|