Problem with my code, please help :) "In an assignment A(I) = B, the number of elements in B and I must be the same"

1 次查看(过去 30 天)
I'm doing my first matlab assignment and my code isnt working and im not quite sure about the problem with it, or if my code is efficient enough.
The assignment is to calculate the trajectories of different guns/bullets and show the convergence as the timestep is reduced. I need to find a way to stop the timestep reducing when it is close enough to the proper figure, within 2%.
I have also tried to plot the trajectories of the bullets and u and v as a function of horizontal distance and the "bullet drop' which is how far vertically the bullet has droppped
Any advice anyone has would be really helpful because im feeling a bit lost about the whole assignment! thanks for your time! :) | %loop for trajectory calculations %Authors: Penny Wood
clear
clc
m=0.033; %mass
d=0.018; %diameter
A=pi*(d/2)^2; %area of bullet
Cd=0.5; %drag coefficient
t=1;
p=1.2; %air density
g=9.81; %acceleration due to gravity
nsteps=1000;
x=zeros(1,nsteps+1);
x(1)=0;
y=zeros(1,nsteps+1);
y(1)=1.7;
u=zeros(1,nsteps+1); %horizontal acceleration array
u(1)=240;
v=zeros(1,nsteps+1); %verticalacceration array
v(1)=0;
V=zeros(1,nsteps+1);
V(1)=240;
bulletdrop=zeros(1,nsteps+1);
bulletdrop(1)=0;
endpoint=100000;
for I=1:1:endpoint ;
dt=[1:1/I:10];
npts=length(dt);
for J=1:npts;
if y(I)<=0;
break
else
V(I+1)=sqrt((u(I))^2+(v(I))^2);
u(I+1)=u(I)-dt*((Cd*A*p)/(2*m))*u(I)*V(I);
x(I+1)=x(I)+dt*((u(I+1)+u(I))/2);
v(I+1)=v(I)-dt*((Cd*A*p)/(2*m))*v(I)*V(I)+g*dt;
y(I+1)=y(I)-dt*(v(I+1)+v(I))/2;
bulletdrop(I+1)=1.7-y(I+1);
end
end
end
plot(x,y)
plot(bulletdrop,y)
plot(u,y)
plot(v,y)
trajectory= y

回答(1 个)

Paulo Silva
Paulo Silva 2011-9-3
There are several mistakes in your code, for example:
u(I+1)=u(I)-dt*((Cd*A*p)/(2*m))*u(I)*V(I);
Doesn't work because dt is a vector and you try to store a vector on a position of the array u, perhaps you want to select just a value of the vector dt like this:
u(I+1)=u(I)-dt(J)*((Cd*A*p)/(2*m))*u(I)*V(I);
Another error, nsteps is just 1000 so your y got 1001 values but in the next code lines you have y(I+1) with I going from 1 to 100000 so you try to access index positions not present on the y vector thus another error.

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by