Attempting to write algorithm, getting error "Attempted to access ys(:,2); index out of bounds because size(ys)=[2,1]"
Show older comments
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
More Answers (1)
Walter Roberson
on 23 Nov 2011
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
yasmine
on 16 Dec 2011
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
Categories
Find more on Matrix Indexing 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!