필터 지우기
필터 지우기

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.

조회 수: 7 (최근 30일)
%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

채택된 답변

Aykut Satici
Aykut Satici 2014년 9월 3일
편집: Aykut Satici 2014년 9월 3일
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')

추가 답변 (1개)

ebru
ebru 2014년 9월 8일
Hey Aykut, really appreciate your help.

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by