MATLAB: Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 0-by-0.

projectile

I'm writing code where I must use ode45.
Here's my function:
function [zdot]= projectile_eoms(t,z)
global m rho Cd A v g
zdot(1,1)=z(2);
zdot(2,1)=(-0.5*rho*v^2*Cd*A*z(2))/m;
zdot(3,1)=z(3);
zdot(4,1)=g-(0.5*rho*v^2*Cd*A*z(4))/m;
return
end
And here is my ode45 m-file:
clear all; clc
%Problem 4 a
global m rho Cd A v g
m=10;
rho=1.2;
Cd=1;
A=0.5;
theta=0.785398;
g=9.81;
t=0:0.001:1;
z0=[0 5*cos(theta) 0 5*sin(theta)]';
[t,z]=ode45(@projectile_eoms,t,z0);
plot(t,z(:,1))
grid on
xlabel('x');
ylabel('y');
When I try running the m-file, I get this message:
Unable to perform assignment because the size of the left side is 1-by-1 and the
size of the right side is 0-by-0.
Error in projectile_eoms (line 4)
zdot(2,1)=(-0.5*rho*v^2*Cd*A*z(2))/m;
What am I doing wrong and how do I fix it?

Best Answer

You defined v as a global variable but never assigned a value, which causes the error inside projectile_eoms.
clear all; clc
%Problem 4 a
global m rho Cd A v g
m=10;
rho=1.2;
Cd=1;
A=0.5;
theta=0.785398;
g=9.81;
v = 1; % <---- add this
t=0:0.001:1;
z0=[0 5*cos(theta) 0 5*sin(theta)]';
[t,z]=ode45(@projectile_eoms,t,z0);
plot(t,z(:,1))
grid on
xlabel('x');
ylabel('y');
Also, see why using global variables is a bad idea. You should define these variables inside the function projectile_eoms: https://www.mathworks.com/matlabcentral/answers/51946-systematic-do-not-use-global-don-t-use-eval