I have to employ the newton raphson algorithm to find the positive real roots of f(x)=2xln(X)-1. I need to create a function m-file to do so. This is my first matlab assignment and I'm not really familiar with it. I don't really know how to go about the iteration and I'm not very confident with creating the function either. Any help would be greatly appreciated.
MATLAB: Newton Raphson m-file
function m-filenewtonraphson
Related Solutions
Hi,
Refer to the following code:
The following code performs Gauss-Seidel...
clcclearclose allA=[5 -2 3 0 6; -3 9 1 -2 7.4; 2 -1 -7 1 6.7; 4 3 -5 7 9; 2 3.5 6.1 -4 -8.1];b=[-1 2 3 0.5 3.1]';x=linspace(0,0,length(A))';n=size(x,1);normVal=Inf;nmax=1000; %number of maximum iterations which can be reached%tol=1e-3; % Tolerence for method%iter=0;while normVal>tol && iter<nmax x_old=x; for i=1:n guess=0; for j=1:i-1 guess=guess+A(i,j)*x(j); end for j=i+1:n guess=guess+A(i,j)*x_old(j); end x(i)=(1/A(i,i))*(b(i)-guess); end iter=iter+1; normVal=norm(x_old-x); endfprintf('Solution of the system is : \n%f\n%f\n%f\n%f\n%f in %d iterations',x,iter);
Output:
0.551479
0.469276
-0.595161
-0.649082
-0.171448 in 86 iterations
Tips:
The convergence properties of the Gauss-Seidel method are dependent on the matrix A. Namely, the procedure is known to converge if either:
- A is symmetric positive-definite
https://www.mathworks.com/help/matlab/ref/chol.html (chol, only for symmetric matrix) [~,p] = chol(A)
OR
- A is strictly or irreducibly diagonally dominant
(Diagonal Dominant)
The Gauss-Seidel method sometimes converges even if these conditions are not satisfied.
Although you can prove that the methods converge if A has all eigenvalues positive from the above conditions (but not the only convergence criterion).
Hope it helps!!
Hello Mary,
The problem is with the function:
diff(h(x))
This function operates with vectors and it only computes the difference. Also, to obtain the derivative you need to divide by an appropriate step size. You have two options here:
- Compute the exact derivative with a symbolic asistant (or by hand ...) and then add to your code in line 16.
- Approximate the derivative with a centered finite difference (or backward,forward).
I used here the second option,
x0 = 0.01; %Guess for initial x
x=x0;dx = 1e-3; % Step size for the centered finite difference
for i=0:100000 y=x; m = (h(x+dx) - h(x-dx)) / (2*dx); % centered finite difference
x = y-(h(x)/m); if x==y break endend
Best.
Best Answer