How do I re-use values calculated in a while loop?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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;
0 Commenti
Risposte (1)
Benjamin Thompson
il 1 Dic 2022
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 Commenti
Benjamin Thompson
il 1 Dic 2022
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.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!