Attempting to write algorithm, getting error "Attempted to access ys(:,2); index out of bounds because size(ys)=[2,1]"

Hi i am trying to implement an rk3 algorithm to solve ivp of the form y' = Ay + b(x) where A is an nxn matrix and b is a vector. When i attempt to use it i encounter the error "Attempted to access ys(:,2); index out of bounds because size(ys)=[2,1]". Here is my code:
{function [x, y] = MyRK3(A, bvector, y0, interval, N)
h = (interval(2) - interval(1))./N;
x(1) = interval(1);
y(:,1) = y0;
ys(:,1) = A*y(:,1) + feval(bvector, x(1));
for i = 1 : N
x1 = x(i) + h;
y1 = y(:,i) + h*ys(:,i);
ys1 = A*y1 + feval(bvector, x1);
x2 = x(i) + h;
y2 = 3/4.*y(:,i) + 1/4.*y1 + 1/4.*h.*ys1;
ys2 = A*y2 + feval(bvector, x2);
x(i+1) = x(i) + h;
y(:,i+1) = 1/3.*y(:,i) + 2/3.*y2 + 2/3.*h.*ys2;
end}
Could you please tell me what i've done wrong to bring about this error,
many thanks,
Tristan

 Accepted Answer

ys has only one column because you assigned it like this:
ys(:,1) = A*y(:,1) + feval(bvector, x(1));
I don't know what you passed in for N but if it's greater than 1 you're going to have a problem at this line:
y1 = y(:,i) + h*ys(:,i);
because i goes up to as great as N. So if i = 2, you'd try to reference ys(:,2) which doesn't exist.
Pretty basic stuff. By the way, do you know how to use the debugger? (I'm guessing you haven't yet learned this crucial skill.)

2 Comments

thanks for the answer, unfortunately no, i am very new to matlab. I'll give it a look
also, i changed the 1 to N, is this the correct solution?

Sign in to comment.

More Answers (1)

Consider your line
ys(:,1) = A*y(:,1) + feval(bvector, x(1));
As ys is not defined before that point, ys will be defined as an array with some number of rows and 1 column -- also known as a column vector.
Then in the "for loop, when "i" is 2 or larger, your statement
y1 = y(:,i) + h*ys(:,i);
attempts to access ys(:,2) or higher. But there is no 2nd or higher column.
There is no adjustment to the code that suggests itself to me, other than that possibly you should be accessing ys(:,1) instead of ys(:,i)

1 Comment

i have the same problem, i attempt to access a number out of bounds in the 5th line, how can i overcome this with code:
NOC=1;
P1=size(Q1);
for ii= 1:size(Q1)
for jj= 1:size(Q1)
if(Q1(ii,jj)==Q1(ii,jj+1))
NOC=NOC+1;
end
if(NOC == 8)
P1(ii,jj)=Q1(ii,jj);
end
end
end
Thank you

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!