"Matrix Dimensions Must Agree" Debug

1 次查看(过去 30 天)
I am writing a code for the motion of a projectile, where I want the results to plot 5 graphs. My issue lies within the y(n+1) part of the code. I have tried both using and not using the "." with my multiplication and division, to no avail. Thank you in advance for the help!
NOTE: My plot should stop once the 'y' value is less than 0, because this is when the projectile hits the ground.
clear; clc;
g=9.81; %m/s/s
vo=100; %m/s
theta=[15:15:85]; %degrees
yo=1; %m
xo=0; %m
y(1)=1; %initial position y in meters
x(1)=0; %initial position x in meters
t(1)=0;
dt=.1;
n=1;
while y(n) >0
t(n+1)=n+dt;
y(n+1)=yo+(vo.*sin(theta).*t)-((g./2).*(t^2));
x(n+1)=xo+(vo.*cos(theta).*t);
n=n+1;
end
plot(x,y)
  5 个评论
Bailey Smith
Bailey Smith 2018-5-31
I meant when y reaches 0. My bad. I want to stop plotting when the projectile hits the ground.
Walter Roberson
Walter Roberson 2018-5-31
You are tracking multiple objects, one for each angle in theta. You need to decide whether you want to stop when the first one hits the ground, or when they have all hit the ground. If it is when they have all hit the ground, you have to decide what you want to do with the ones that went below the ground while the others were still falling.

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2018-5-31
t(n+1)=n+dt;
so t is getting larger as you go.
t starts at as scalar before the loop, and in the first iteration of the loop expands to a vector of length 2
y(n+1)=yo+(vo.*sin(theta).*t)-((g./2).*(t^2));
theta is a vector of length 5, and you have sin(theta).t . But t is a vector of length 2, and you cannot .* between a 1 x 5 and a 1 x 2.
Then in the right hand part of the expression, you have t^2 but t is a vector and you cannot ^2 a vector. You can ^2 a square matrix, or you can .^2 a vector.
yo+(vo.*sin(theta).*t(n+1))-((g./2).*(t(n+1)^2))
would get rid of the problems about t being a vector of a different size than theta. However, you would still have the difficulty that theta is a vector of length 5, so you are going to be calculating 5 different results and trying to store them in the single location y(n+1)
clearvars
g=9.81; %m/s/s
vo=100; %m/s
theta=[15:15:85]; %degrees
yo=1; %m
xo=0; %m
y(1, :) = 1 * ones(size(theta)); %initial position y in meters
x(1, :) = 0 * ones(size(theta)); %initial position x in meters
t(1)=0;
dt=.1;
n=1;
while y(n) >0
t(n+1)=n+dt;
y(n+1,:)=yo+(vo.*sin(theta).*t(n+1))-((g./2).*(t(n+1)^2));
x(n+1,:)=xo+(vo.*cos(theta).*t(n+1));
n=n+1;
end
plot(x,y)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by