How could i write a matlab code for newton's iteration for implicit functions. I've bagan to write it up but I'm stuck at the loop.

8 visualizzazioni (ultimi 30 giorni)
%the x is held fixed, from [-5:1001:5]. the initial for y=5. I either have to complete it for 40 iterations or for abs(f(x,yn))<10^-10
syms x y ynew
x= -5;
y= 5;
f = exp(y-x.^2)-sin(y)-pi;
ynew = y + f./diff(f);
while abs(f)<1e-10;
y=ynew
x= x+ 0.00999001
end

Risposta accettata

Aykut Satici
Aykut Satici il 3 Set 2014
Modificato: Aykut Satici il 3 Set 2014
I understand that you would like to find the value of y such that f(x,y) = 0 using Newton's iteration.
Since you are after an iterative solution, I would recommend avoiding symbolic variables and sticking to doubles. The steps to obtain a solution are:
  1. Define the function
  2. Define the gradient of this function along the y-direction
  3. Choose the starting point
Once these steps are achieved, the code begins an iteration on y which hopefully converges to the solution. Note that your starting point must be in the region of attraction for the iteration to converge. Otherwise, the iteration might get stuck on (converge to) a local minimum of the function that is not necessarily equal to zero.
The easy part is to define the starting point:
maxIter = 40; % Maximum number of iterations
xSpan = linspace(-2,2,1001); % Span of the variable x
y = NaN(maxIter,length(xSpan)); % Initialize the variable of interest to NaN
y(1,:) = 5; % Set the starting point for y to 5 for all x
Next, we need to define our function and the its gradient along the y-direction:
f = @(x,y) exp(y-x.^2) - sin(y) - pi; % Define the function
dfy = @(x,y) exp(y-x.^2) - cos(y); % Define the gradient of the function
Finally, for every different value of x, we perform the Newton iteration:
% Loop over all values of x
j = 1;
for x = xSpan % Newton iteration for every different x value
i = 1;
while ( i < maxIter && abs(f(x,y(i,j))) > 1e-10 ) % Newton iteration
y(i+1,j) = y(i,j) - dfy(x,y(i,j)) \ f(x,y(i,j));
i = i + 1;
end
j = j + 1;
end
You can then play with the solution. Here is a visualization of the convergence for x = 1:
% Visualize
col = find(xSpan == 1); % Observe the convergence for x = 1
figure(1), clf
plot(abs(f(xSpan(col),y(:,col))))
xlabel('Iterations')
ylabel('$\left| f(x,y_k) \right|$', 'Interpreter', 'LaTeX')

Più risposte (1)

ebru
ebru il 8 Set 2014
Hey Aykut, really appreciate your help.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by