Newton's method(calculating the angel)
조회 수: 2 (최근 30일)
이전 댓글 표시
%% 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
John D'Errico
2020년 3월 15일
편집: John D'Errico
2020년 3월 15일
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.
답변 (1개)
Sriram Tadavarty
2020년 3월 16일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!