1
votes

I'm trying to write the Newton Raphson method in Matlab but first I have to find the derivatives of my function. I'm new to Matlab and I don't get the results that I need. I've tried different methods but nothing helps, I think I don't get the results that I want because I'm not familiar with the Matlab syntax. Here is my code:

1) First I have my function in a file called fun1.m

function y = fun1(x)
   y = exp(x) - 2*x - 2;

2) Then I go to my other file where I try to write the Newton Raphson method

%my bounds
low = 0;
high = 3;

%my initial guess will be determined from product of the function of the file fun1.m and the derivative of that function for the boundaries that i've given. If one of the products is greater then zero than this value will be my first guess. This is what I wrote

 f = fun1(x);
 f1 = diff(f);
 f2 = diff(f,2);

 %As a result if I put out the semicolons I get f1 = 0 and f2 = 0
 %I want to compute these products
 prod1 = f(low) * diff(f(low))
 prod2 = f(high) * diff(f(high))

How should I go on with this? I've also tried file handles and as a result after differentiating I got [ ]. It also isn't necessary to have the function in another file but because I have to do 3 methods that use the same function I thought it would be better to get the function from a file rather than write it everytime. So how can I get the function and put the low and high values and differentiate them?

1

1 Answers

0
votes

After the step f=fun1(x), f will simply be the value of f at the position x. Now diff will try to calculate the difference between elements of a vector. As you only have one value in f, diff will return [].

If you have the MATLAB Symbolic Toolbox, you can calculate the symbolic derivatives. Note that the functions are still called diff, but these are different functions! For details compare the help pages of the MATLAB Diff and the Symbolic Diff functions.

syms x
f = exp(x) - 2*x - 2;
df = diff(f);
ddf = diff(df);

Then you can evaluate these functions at the needed points

prod1 = subs(f,x,low) * subs(df,x,low);
prod2 = subs(f,x,high) * subs(df,x,low);

Now prod1 and prod2 are still symbolic numbers and not "normal" double values. In this example case, prod1=1 and prod2=8-exp(3). To convert the numbers to double, simply

p1 = double(prod1);
p2 = double(prod2);