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

조회 수: 1(최근 30일)
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 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표시 이전 댓글 수: 1숨기기 이전 댓글 수: 1
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.

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

### 범주

Find more on Equation Solving in Help Center and File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by