简体   繁体   中英

Matrix indexing error in MATLAB

I keep getting this error 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 statement 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

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

在MATLAB中,向量和矩阵从1开始编制索引。因此,代码的第一行无效,因为r上的索引为0。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM