Newton's method(calculating the angel)
2 views (last 30 days)
Show older comments
%% Newton's method
w = 30; h = 30; c = 3.5; % In inches
f = @(theta) w*sind(theta) - h*cosd(theta) - c;
fp = @(theta) w*cosd(theta)+h*sind(theta);
theta_newt(1) = 49.49; % Set initial guess
tol=0.4771;
n=1;
while n==1:50
fe = f(theta_newt(1));
fpe = fp(theta_newt(1));
theta_newt(n+1) = theta_newt(n) - fe(n)/fpe(n);
if theta_newt(n+1)>= 49.73-tol || theta_newt(n+1)< 49.73+tol
theta=theta_newt(n+1);
break
end
n = n + 1;
end
I am trying to run this code but it seems that the loop isnt working properly
how would I fix that?
Also,How would I show how many iteration it takes to come up with the wanted angle?
2 Comments
John D'Errico
on 15 Mar 2020
Edited: John D'Errico
on 15 Mar 2020
Why are you using Newton's method anyway? Why not use fzero? Never write your own solver code.
That you should not be writing your own solvers is evidenced by you use of non-working constructs. For example:
while n==1:50
That is not how you construct a while loop.
Answers (1)
Sriram Tadavarty
on 16 Mar 2020
Hi Ahmed,
To make the code working, perform the following changes:
- Update the while loop with proper condition
- Calculate fe and fpe for each n
- Do not access the fe and fpe with indexing variable, since it is a scalar
This leads to following update in the while loop
while n <= 50 % Proper loop condition
fe = f(theta_newt(n)); % Calculate for each n
fpe = fp(theta_newt(n)); % Calculate for each n
theta_newt(n+1) = theta_newt(n) - fe/fpe; % Remove the indexing here
if theta_newt(n+1)>= 49.73-tol || theta_newt(n+1)< 49.73+tol
theta=theta_newt(n+1);
break
end
n = n + 1;
end
This will fix the loop operation.
Hope this helps.
Regards,
Sriram
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!