## A(:) = B, the number of elements in A and B must be the same. error, what am I doing wrong?

### John Albrecht (view profile)

on 7 Mar 2018
Latest activity Answered by Walter Roberson

### Walter Roberson (view profile)

on 7 Mar 2018
figure(1); clf
%Time Step
Ts = 0.001; % time step
t=0:Ts:200 ;
% perameters
a1 = 1.25;
a2 = 1;
y = 0.001;
z= 0;
gain = 1.8;
x=0;
for k=2:length(t)
dxdt = y;
d2xdt2 = z;
d3xdt3 = (gain*x-a1*y-a2*z-gain*(x.^3));
x(k) = x(k-1)+dxdt*Ts;
y(k) = y(k-1)+d2xdt2*Ts;
z(k) = z(k-1)+d3xdt3*Ts;
end
figure(1); clf
plot (x,y,'b-'); hold on

### Tags ### Roger Stafford (view profile)

on 7 Mar 2018

The problem lies with the lines
x(k) = x(k-1)+dxdt*Ts;
y(k) = y(k-1)+d2xdt2*Ts;
z(k) = z(k-1)+d3xdt3*Ts;
On the second pass through your for-loop, the variables 'dxdt', 'd2xdt2', and 'd3xdt3' become two-element arrays. However, you are then attempting to enter these into one-variable values of x(k), y(k), and z(k). They won't fit, hence the error message. You need to reconsider what it is you wish to enter into x(k), y(k), and z(k). ### Walter Roberson (view profile)

on 7 Mar 2018

x=0;
That initializes x(1) = 0
for k=2:length(t)
...
x(k) = x(k-1)+dxdt*Ts;
so when k = 2 (the first iteration), x(2) is going to be assigned. So after that x will be a vector rather than a scalar.
d3xdt3 = (gain*x-a1*y-a2*z-gain*(x.^3));
That uses all of x, so from k = 3 and later, d3xdt3 will be a vector because x became a vector by the end of k = 2
z(k) = z(k-1)+d3xdt3*Ts;
d3xdt3 is a vector, so the right hand side is a vector, but you are trying to assign the vector into the single location z(k)