MATLAB: Size of matrix keeps changing even after pre-allocating

index out of boundsMATLAB and Simulink Student Suiteode23ssize of matrix

I am using ode23s function (x,y) to solve 12 differential equations over 8 equal time intervals and 2 parameters are supplied. At each interval, one parameter of the function changes. I want the value of y after each iteration to be stored in the other parameter. I initialized y to be a [12,12] matrix. But the size of the matrix changes when I run the program and gives an "index out of bounds" error. Is my initialized size of matrix wrong or is it due to some other reason?
My code:
for i=1:dt:t
tspan=[i i+dt];
y=zeros(12,12);
wrapper=@(x,y)bulk_polymerization_MMA1(y,FVr_temp(1,k));
[x,y]=ode23s(wrapper,tspan,init_con);
ys1=y(length(y),1);
ys2=y(length(y),2);
ys3=y(length(y),3);
ys4=y(length(y),4);
ys5=y(length(y),5);
ys6=y(length(y),6);
ys7=y(length(y),7);
ys8=y(length(y),8);
ys9=y(length(y),9);
ys10=y(length(y),10);
ys11=y(length(y),11);
ys12=y(length(y),12);
init_con=[ys1,ys2,ys3,ys4,ys5,ys6,ys7,ys8,ys9,ys10,ys11,ys12];
Error: Attempted to access y(12,1); index out of bounds because size(y)=[11,12].
Error in bulkMMA_objfun (line 39) ys1=y(length(y),1);

Best Answer

You do not want ys1=y(length(y),1), because length replies the size of the longest dimension. You want:
ys1 = y(end, 1); % Or ys1=y(size(y, 1), 1);
But the pile of temporary "ys" variables is cruel. Better use this:
init_con = y(end, 1:12);