MATLAB 中的矩阵索引错误
我在 Matlab 中不断收到此错误:
尝试访问r(0,0);索引必须是正整数或 合乎逻辑的。
错误==>龙伯格 15 岁
我用 Romberg(1.3, 2.19,8)
运行它,
我认为问题是该陈述不合逻辑,因为我将其设为肯定,但仍然遇到相同的错误。有人知道我能做什么吗?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有两行使用 0 来索引,而在 Matlab 中则不能:
以及
当 j==1 或 i==1 时。
我建议您从 2 开始运行循环,并将指数 i 和 j 分别替换为 (i-1) 和 (j-1)。
编写循环
顺便说一句:您可以像
编写 f_of_x 一样
There are two lines where you're using 0 to index, which you can't in Matlab:
and
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
as
if you write f_of_x as
在 MATLAB 中,向量和矩阵从 1 开始索引。因此,代码的第一行无效,因为
r
上的索引为 0。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.您的下标为零
这在 MATLAB 中是不可能的 — 所有索引都从 1 开始。
You have zero subscripts in
This is impossible in MATLAB -- all indices start form 1.