简体   繁体   English

MATLAB中的矩阵索引错误

[英]Matrix indexing error in MATLAB

I keep getting this error in Matlab: 我在Matlab中不断收到此错误:

Attempted to access r(0,0); 试图访问r(0,0); index must be a positive integer or logical. index必须是正整数或逻辑。

Error in ==> Romberg at 15 错误==> Romberg at 15

I ran it with Romberg(1.3, 2.19,8) 我用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: 有两行你使用0来索引,你不能在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. 当j == 1或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. 我建议你从2开始运行你的循环,并分别用(i-1)和(j-1)替换指数i和j。

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 如果你写f_of_x为

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. 这在MATLAB中是不可能的 - 所有索引从1开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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