- Define the function
- Define the gradient of this function along the y-direction
- Choose the starting point
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.
13 次查看(过去 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
0 个评论
采纳的回答
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:
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')
0 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!