Not sure how to fix index out of bounds

1 view (last 30 days)
Dominic
Dominic on 2 Sep 2014
Answered: Guillaume on 2 Sep 2014
Hey guys here is my code
%%Intitial Conditions
N = 1000;
a = 0;
b = 2;
p = 0;
q = 0;
h = (b-a)/N;
x = linspace(a,b,N);
y = exp(-x.^2);
%%Simpsons Rule
S = (h/3).*y(1);
for i = 2:N/2
p = p + (h/3).*y(2*i-1);
end
for i = 2:N/2-1
q = q +(h/3).*y(2*i);
end
S = S + 4*p + 2*q + (h/3)*y(N);
disp(S)
%%Order of error
In(i) = S;
for i = 1:N
r = (In(i)-In(2.*i))./(In(2.*i)-In(4.*i));
end
P = log(r)/log(2);
disp(P)
I get this error
??? Attempted to access In(500); index out of bounds because numel(In)=499.
Error in ==> Simp1 at 24 r = (In(i)-In(2.*i))./(In(2.*i)-In(4.*i));
I understand that In has a value at 499 and that it cant take on a value at 500 but Im clueless as to how to fix this.
Any assistance would be greatly appreciated.

Answers (1)

Guillaume
Guillaume on 2 Sep 2014
A few problems with your code. First:
In(i) = S;
Looks very suspicious. As i is the last value reached in the last for loop. If that's really what you wanted to do then
In = zeros(1, 499);
In(499) = S;
would be a lot clearer. But I suspect that's not what you wanted to do and you're missing somewhere a declaration of In.
Secondly:
for i = 1:N
r = (In(i)-In(2.*i))./(In(2.*i)-In(4.*i));
end
Three problems here.
- You haven't put anything in In so r = 0/0 = NaN
- Since i goes up to N = 1000, you need at least 4000 elements in In for In(4*i) to be valid
- You're overwriting r on each iteration of the loop.

Community Treasure Hunt

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

Start Hunting!