How to use nested FOR loop to create a matrix of answers?

1 visualizzazione (ultimi 30 giorni)
Hello, I'm relatively new to MATLAB and I'm struggling on producing a matrix with a size of 30x6 using nested FOR loops.
I want 30 different values for the variable 'theta' between 0-90 and 6 different values for the variable 'Vs' between 0-60, put it through the equations and return the answers as a 30 by 6 matrix. I've tried having theta = (3:3:90)' and Vs = 10:10:60 but that's as far as my knowledge goes. I'm not entirely sure where to put the for loops in this code either.
Thanks in advance, I appreciate any kind of help.
% INPUT DATA
% Specified constants:
k = 0.02;
g = 9.81;
dt = 0.01;
% Input the initial condition:
theta = 55; % Launch angle in degrees.
rads = theta*(pi/180); % Converts degrees to radians.
Vs = 10; % Launch speed m/s.
u(1) = Vs*cos(rads);
v(1) = Vs*sin(rads);
% Launch pad location:
x(1) = 0;
y(1) = 0;
% Compute approximate solution of the trajecotry of flight.
% Repeat up to 2000 time, i.e., until ball hits the ground.
for n = 1:1:2000
u(n+1) = u(n)- dt * (k * sqrt(u(n)^2+v(n)^2) * u(n));
v(n+1) = v(n)- dt * (k * sqrt(u(n)^2+v(n)^2) * v(n) + g);
x(n+1) = x(n) + u(n) * dt;
y(n+1) = y(n) + v(n) * dt;
% Determination of when the object hits ground:
if y(n+1) < 0
slope = (y(n+1) - y(n))/(x(n+1) - x(n));
b = y(n) - slope * x(n);
xhit = - b/slope;
plot(x,y)
fprintf(' The length of the shot = %5.2f \n', xhit)
end
% Once object hits terminate the computations with a break:
if y(n+1) < 0
break;
end
end
The length of the shot = 8.27

Risposta accettata

Jan
Jan il 15 Nov 2022
Modificato: Jan il 15 Nov 2022
thetaL = 3:3:90;
VsL = 10:10:60;
... Other constants
Result = NaN(numel(thetaL), numel(VsL));
for itheta = 1:numel(thetaL)
theta = thetaL(itheta);
rads = theta*(pi/180); % Converts degrees to radians.
for iVs = 1:numel(VsL)
Vs = VsL(iVs);
... Your code:
u(1) = Vs*cos(rads);
v(1) = Vs*sin(rads);
...
Result(itheta, iVs) = xhit;
end
end
  4 Commenti
Jan
Jan il 24 Nov 2022
Only to fill the output with values initially, which can be recognized. Maybe your code does not find a solution for some inputs.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Programming in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by