MATLAB: Function definition is misplaced or improperly nested error

there is problem in writing differential equation.

function [v,y] = call_dstate()
for h_s = [1 3 2 ]
for h_d = [3 1 6]
for MA = [1.5 2.5 3.5]
for D_d = 0.0254*[1.25 1.75 2.25]
for D_s = 0.0254*[1.25 1.75 2.25]
for D_p = 0.0254*[2.5 3.5 4.5]
for L = [0.10 0.14 0.18]
y = [0.15 0.094];
v0 = 0.01;
m =64.5;
x = 0.7;
b = 0.625;
a = 0.250;
g = 9.8;
A_d = (D_d.^2)*3.14*0.25;
D_s = 0.0254;
A_s = (D_s^2)*3.14*.25;
l_d = 4.572;
l_s = 6.096;
A_p = ((D_p).^2)*3.14*0.25;
m_p = 0.2;
rho = 1000;
uk = 0.06;
uf = 0.4;
up = 0.00089;
h = 0.001;
t_w= 0.05;
A_w = t_w*D_p.*3.14;
z=0.2946*MA-0.1761;
M_tr= 2;
L_tr=0.5;
P=173.7;
R_pin=0.05;
M_T=2*m_p*(A_d/A_p)^2+(L+l_d+l_s)*rho*((A_d)^2/A_p)+(2*M_tr*L_tr^2/a^2)+z^2*MA^2*m*(A_d/A_p)^2;
c0=(1-2*x)*A_p*P/(A_d*M_T);
c1=(rho*g*(h_s*A_s+h_d*A_d+L*A_p)+z(1)*m*g*MA)/M_T;
c2=(2*rho*g*A_p)/M_T;
c3=(2*uf*b+25.12*up*L*h)*A_d/(h*M_T*A_p);
c4=(0.124*rho^0.75*up^0.25*[l_d*D_d^0.25+l_s*D_s^0.25]*(A_d/A_s)^1.75)/M_T;
c5=rho*[((A_d)^2/A_s)*[0.5+0.5+0.2+0.4+0.5]+0.5*((A_d)^2/A_p)+A_d*(0.5+0.4+0.2+1)+0.5*((A_d)^2/A_p)]/(2*M_T);
c6=uk*R_pin*[((2*M_tr*L_tr*A_d^2)/(a^2*A_p^2))+((m*MA*z^2*A_d^2)/(a*A_p^2))];
% dstate evaluates r.h.s. of the ode
[y,v] = ode45( @dstate ,y ,v0);
disp([y,v])
function dvdy = dstate(y,v)
v = ([c0]/v^2)-([c1]/v)-([c2]*y/v)-[c3]-[c4].*v^0.75-[c5]*v-([c6]*v/(sqrt(a^2-(y-0.047)^2)));% This is ODE
end
end
end
end
end
end
end
end
end
%%
I have used combination of different parameters using for loops. But differential equation is not getting solved. How should I tackle with this?

Best Answer

Once the code is aligned properly then the problem is clear:
for ...
for ...
for ...
for ...
for ...
for ...
for ...
...
function dvdy = dstate(y,v)
v = ([c0]/v^2)-([c1]/v)-([c2]*y/v)-[c3]-[c4].*v^0.75-[c5]*v-([c6]*v/(sqrt(a^2-(y-0.047)^2)));% This is ODE
end
end
end
end
end
end
end
end
Functions cannot be defined inside of loops or of any other code constructs. They can be defined at file level only.
You will need to replace that invalid function definition with an anonymous function:
Note that your code contains many syntax warnings that I strongly suggest that you fix.