How do I re-use values calculated in a while loop?

조회 수: 5 (최근 30일)
Shivam Naik
Shivam Naik 2022년 12월 1일
댓글: Benjamin Thompson 2022년 12월 1일
I have code that takes two values of angle and computes an ODE with each angle to calculate the highest altitude of a projectile. This altitude is compared with the desired altitude and an error value is taken. The shooting method formula is used to then calculate the next angle for iteration. I have had success in manually repeating the steps to obtain a perfect angle however I am struggling to incorporate this in a while loop. I am trying to use the values of Theta 2 and Theta 3 from the first part of the while loop to be re-input back into the loop multiple times until the error is close to zero. I have either had "function or variable unrecognised" or been stuck in an infinite loop where the loop repeats with the same angles (Theta1 and Theta2).
Any ideas? Thanks
function requiredAngle = shootingMethod1(Theta1, Theta2, apogee)
% This function uses two guesses of angle for projectile launch and
% implements the shooting method formula to iterate the correct angle to reach a
% certain apogee
% Solve ODE, find apogee, find error
[~,~,guessHeight1] = ivpSolver(0,0,Theta1,1,300);
Apogee1 = max(guessHeight1);
error1 = apogee - Apogee1;
% Solve ODE, find apogee, find error
[~,~,guessHeight2] = ivpSolver(0,0,Theta2,1,300);
Apogee2 = max(guessHeight2);
error2 = apogee - Apogee2;
% error 2 has a negative starting value
while abs(error2) > 1
% Calculate value for guess 3 using shooting method formula
Theta3 = Theta2 - ((Theta2-Theta1)/(error2-error1))*error2;
% Solve ODE, find apogee
[~,~,guessHeight3] = ivpSolver(0,0,Theta3,1,300);
Apogee3 = max(guessHeight3);
% should loop if error2 is not zero
error2 = apogee - Apogee3
% set theta 3 and theta 2 as next two guess
Theta1 = Theta2;
Theta2 = Theta3;
end
requiredAngle = Theta3;

답변 (1개)

Benjamin Thompson
Benjamin Thompson 2022년 12월 1일
Theta1 and Theta2 have not been defined and given a value at the first reference. You should assign an initial value to Theta1 and Theta2 before the while loop.
  댓글 수: 2
Shivam Naik
Shivam Naik 2022년 12월 1일
Are Theta1 Theta2 not predefined in the function input? Also I have tried this and it still results in errors.
Benjamin Thompson
Benjamin Thompson 2022년 12월 1일
What line does the error occur at? Have you tried stepping through the code using the debugging features in the editor? Theta3 would be undefined if the while loop was never entered.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by