Why am I getting Complex number results?

조회 수: 26 (최근 30일)
Ethan Fritz
Ethan Fritz 2020년 10월 30일
댓글: Ethan Fritz 2020년 11월 1일
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?

답변 (1개)

David Goodmanson
David Goodmanson 2020년 10월 31일
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
Ethan Fritz
Ethan Fritz 2020년 11월 1일
Thank you very much sir. It worked out very well. Thank you again?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Language Fundamentals에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by