MATLAB Answers

Error: "In an assignment A(I) = B, the number of elements in B and I must be the same." error

1 view (last 30 days)
afshin Rezaei
afshin Rezaei on 24 Apr 2021
Commented: the cyclist on 26 Apr 2021
Hi, I do not know why I running into this error, I hope you guys can help me, please.
%*********in func3.m********
function xdot = func3(t,x)
global DF1 DF2 d1 d2 fi1 fi2 Beta n ii
Beta=3; n=2; s1=1.5;
z1=0.5; s2=1.8; z2=2;
DF1=0.3*(sin(1*pi*x(1))*sin(2*pi*x(2))*sin(3*pi*x(3))*sin(4*pi*x(4)));
DF2=0.2*(sin(1*pi*x(1))*sin(2*pi*x(2))*sin(3*pi*x(3))*sin(4*pi*x(4)));
d1=0.15*sin(5*t(ii));
d2=0.10*sin(7*t(ii));
u1(ii)=-((Beta+10)*abs(x(1))+2*abs(x(2))+s1(ii)+z1(ii))*sign(s1);
u2(ii)=-(abs(x(1))+(x(1)*x(3))+(0.5+n*abs(x(4))+s2(ii)+z2(ii)))*sign(s2);
fi1=(1.4+0.2*sin(u1(ii)))*u1(ii);
fi2=(1.3+0.2*cos(u2(ii)))*u2(ii);
xdot = zeros(4,1);
xdot(1)= 10*x(2)-10*x(1)+x(4);
xdot(2)= -x(1)*x(3)+Beta*x(1)-x(2)+ DF1+d1+fi1;
xdot(3)=x(1)*x(2) - 8/3*x(3);
xdot(4)=-x(1)*x(3) + n*x(4)+ DF2+d2+fi2;
end
% ====================================================================================
% ********in main.m **********
x=[0.1 2 3 -3];
t=0:0.02:7;
[T,x] = ode23(@func3,[-20 20 ],x);
x=x(2,:);
X=x;
Beta(ii+1)=abs(S(1))*abs(x(1));
s1(ii+1)=abs(S(1));
z1(ii+1)=abs(S(1));
s2(ii+1)=abs(S(2));
z2(ii+1)=abs(S(2));
n(ii+1)=abs(x(4))*abs(S(2));
S1(ii+1)=S(1);
S2(ii+1)=S(2);
X(ii+1,:)=x;
D1(ii)=d1;
D2(ii)=d2;
ii;
figure(3)
plot(t(1:end-1),X)
legend('x_1(t)','x_2(t)','x_3(t)','x_4(t)')
figure(4)
plot(t(1:end-1),S1); hold on
plot(t(1:end-1),S2,'g');
legend('S_1(t)','S_2(t)')
figure(5)
plot(t(1:end-2),u1); hold on
plot(t(1:end-2),u2,'g');
legend('u_1(t)','u_2(t)')
Error:
In an assignment A(I) = B, the number of elements in B and I must be
the same.
Error in func3 (line 22)
xdot(2)= -x(1)*x(3)+Beta*x(1)-x(2)+ DF1+d1+fi1;
Error in odearguments (line 88)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode23 (line 113)
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0, odeArgs, odeFcn,
...
Error in main (line 11)
[T,x] = ode23(@func3,[-20 20 ],x);

Accepted Answer

the cyclist
the cyclist on 24 Apr 2021
You defined the global variable ii, but never assigned it a value. Therefore, it is an empty array.
Therefore d1 is also an empty array, when you assign it.
Therefore this line
xdot(2)= -x(1)*x(3)+Beta*x(1)-x(2)+ DF1+d1+fi1;
has an empty right-hand side, and a non-empty left-hand side, giving the error you see.
I used the debugger to solve this mystery, by stopping the code just before the error occurred. You might want to learn how to use this powerful tool.
  2 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!