Why am I getting Complex number results?

27 Ansichten (letzte 30 Tage)
Ethan Fritz
Ethan Fritz am 30 Okt. 2020
Kommentiert: Ethan Fritz am 1 Nov. 2020
I am doing an assignment for a course and I'm trying to map the position, velocity and acceleration of an object moving in a 2D fashion. Here is my code:
clear; clc;
rho_i=1.2;
c=6.5*10^-3;
T=300;
alpha=2.5;
theta=(45*pi)/180;
Area=pi*(.406/2)^2;
m=1225;
vi=762;
vxi=vi*cos(theta);
vyi=vi*sin(theta);
D=0.5;
g=9.81;
n=100000;
t=zeros(n,1);
x=zeros(n,1);
y=zeros(n,1);
vx=zeros(n,1);
vy=zeros(n,1);
v=zeros(n,1);
ax=zeros(n,1);
ay=zeros(n,1);
rho=zeros(n,1);
PError=zeros(8,1);
VError=zeros(8,1);
AError=zeros(8,1);
t(1)=0;
vx(1)=vxi;
vy(1)=vyi;
x(1)=0;
y(1)=0;
ax(1)=0;
ay(1)=0;
rho(1)=rho_i;
for j=1:7;
dt=10^(1-j);
for i=2:n;
t(i)=t(i-1)+dt;
vx(i)=vx(i-1)+ax(i)*t(i);
vy(i)=vy(i-1)+ay(i)*t(i);
v(i)=sqrt(vx(i)^2+vy(i)^2);
y(i)=y(i-1)+vy(i)*t(i);
x(i)=x(i-1)+vx(i)*t(i);
ax(i)=((-D*rho(i)*Area)/(2*m))*(v(i)*vx(i));
ay(i)=((-D*rho(i)*Area)/(2*m))*(v(i)*vy(i))-g;
a(i)=sqrt(ax(i)^2+ay(i)^2);
rho(i)=rho_i*(1-(c*y(i)/T)).^alpha;
end
end
I am completely confused as to why I am obtaining complex numbers for values in my arrays. Any ideas?

Antworten (1)

David Goodmanson
David Goodmanson am 31 Okt. 2020
Hello Ethan,
The reason for this is that at step i = 14, the quantity on the third to last line, (1-(c*y(i)/T)) becomes negative, and since it is being taken to the alpha = 2.5 power which is not an integer power, the results are complex.
The y variables are growing far faster than they should because in several places you are using expressions such as
vx(i)=vx(i-1)+ax(i)*t(i);
rather than the correct
vx(i)=vx(i-1)+ax(i)*dt;
It's doable and not causing problems in this case, but I tend not to use i as an index variable due to possible confusion with i = sqrt(-1).
  1 Kommentar
Ethan Fritz
Ethan Fritz am 1 Nov. 2020
Thank you very much sir. It worked out very well. Thank you again?

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Language Fundamentals 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!

Translated by