How to use nested FOR loop to create a matrix of answers?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
Jan
am 15 Nov. 2022
Bearbeitet: Jan
am 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 Kommentare
Jan
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
