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

1 次查看(过去 30 天)
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

采纳的回答

Jan
Jan 2022-11-15
编辑:Jan 2022-11-15
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 个评论
Jan
Jan 2022-11-24
Only to fill the output with values initially, which can be recognized. Maybe your code does not find a solution for some inputs.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by