size of matrix keeps changing even after pre-allocating

1 view (last 30 days)
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);
  1 Comment
Jan
Jan on 20 Jul 2015
Edited: Jan on 20 Jul 2015
I've formatted your code to make it readable. Please use the "{} Code" button for this. Thanks.

Sign in to comment.

Accepted Answer

Jan
Jan on 20 Jul 2015
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);

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!