tags:

views:

82

answers:

3

I keep getting the error( this is in Matlab) Attempted to access r(0,0); index must be a positive integer or logical.

Error in ==> Romberg at 15

I ran it with Romberg(1.3, 2.19,8)

I think the problem is the statment is not logical because I made it positive and still got the same error. anyone got some ideas of what i could do?

function Romberg(a, b, n)

h = b - a;

r = zeros(n,n);

for i = 1:n

    h = h/2;

    sum1 = 0;

    for k = 1:2:2^(i)

        sum1 = sum1 + f(a + k*h);

    end

    r(i,0) = (1/2)*r(i-1,0) + (sum1)*h;

    for j = 1:i

        r(i,j) = r(i,j-1) + (r(i,j-1) - r(i-1,j-1))/((4^j) - 1);

    end

end

disp(r);

end

function f_of_x = f(x)

f_of_x = sin(x)/x;

end
+2  A: 

In MATLAB, vectors and matrices are indexed starting from 1. Therefore, the very first line of your code is invalid because the index on r is 0.

Will
Sorry about that was typo i did not mean to put that first line of code in there.
Ben Fossen
Nevertheless, the same line exists in the middle of the code block. It's trying to assign to `r(i, 0)` which is illegal because 0 is an illegal index into the matrix.
Will
+1  A: 

You have zero subscripts in

r(i,0) = (1/2)*r(i-1,0) + (sum1)*h;

This is impossible in MATLAB -- all indices start form 1.

AVB
+5  A: 

There are two lines where you're using 0 to index, which you can't in Matlab:

r(i,0) = (1/2)*r(i-1,0) + (sum1)*h;

and

r(i,j) = r(i,j-1) + (r(i,j-1) - r(i-1,j-1))/((4^j) - 1);

when j==1 or i==1.

I suggest that you run your loops starting from 2, and replace the exponents i and j with (i-1) and (j-1), respectively.

As an aside: You could write the loop

for k = 1:2:2^(i)

   sum1 = sum1 + f(a + k*h);

end

as

k = 1:2:2^i;
tmp = f(a + k*h);
sum1 = sum(tmp);

if you write f_of_x as

sin(x)./x
Jonas
In case `a` is ever negative, you might want to define `f(x)` as`f_of_x = sin(x)./x; f_of_x(isnan(f_of_x)) = 1;` Or `sinc(x/pi)` would work too.
mtrw

related questions