索引超出矩阵维度弹出错误

时间:2013-11-05 23:15:15

标签: matlab

我正在尝试近似1 / e

我一直收到一条错误,指出索引超出矩阵维度。为什么呢?

n = 0;
eqn = 0;

while abs(eqn - (1/exp(1))) > .0001
n = n+1;
eqn = (1 - (1/n))^n;

end

nsav = n;
appr = eqn;
builtin = 1/exp(1);
fprintf ('The built in value is %.4f\n' , builtin)
fprintf ('The approximation is %.4f\n', appr)
fprintf ('The value of n required for such accuracy is %d\n', nsav)

3 个答案:

答案 0 :(得分:1)

修改

这个答案并没有真正解决用户的问题。但是,由于用户想要的是一个接近1 / e的循环,这里有一些可能性:

一种快速方法:

tic
N = 1e6;
N1 = 1;
N2 = N1 + N - 1;
err_exp = 1e-7;
ctrl = 1;
while ctrl
  n = N1:N2; eqn = (1 - (1 ./ n)) .^ n;
  inds = find(abs(eqn - 1/exp(1)) < err_exp, 1, 'first');
  if ~isempty(inds)
    ctrl = 0;
  else
    N1 = N1 + N;
    N2 = N1 + N - 1;
  end
end
fprintf('n must be at least %d\n', N1 + inds - 1)
toc
% Elapsed time is 0.609669 seconds.

更好的方法是二分法搜索:

tic
N = 1e6;
a = 1 / exp(1);
err_exp = 1e-15;
ctrl = 1;
n = 1;
% 1º Step: find starting values for n1 and n2
while ctrl
  eqn = (1 - (1 / n)) ^ n;
  ctrl = abs(eqn - a) > err_exp;
  if ctrl
    n1 = n;
    n = 2 * n;
  end
end
n2 = n;

% 2º step: search dichotomically between the extremes
ctrl = 1;
while ctrl
  if n2 - n1 < N
    n = n1:n2; eqn = (1 - (1 ./ n)) .^ n;
    n = find(abs(eqn - a) < err_exp, 1, 'first');
    eqn = eqn(n);
    n = n1 + n - 1;
    ctrl = 0;
  else
    n = floor((n1 + n2 + 1) / 2);
    eqn = (1 - (1 / n)) ^ n;
    chck = abs(eqn - a) > err_exp;
    if chck
      n1 = n;
    else
      n2 = n;
    end
  end
end
toc
% Elapsed time is 0.231897 seconds.

[abs(eqn - a), err_exp]
[n1 n n2]

只为了它的乐趣。

答案 1 :(得分:1)

输入whos并确保未列出absexp。如果它们被列为变量,请用以下内容清除它们:

clear abs whos

然后确保此代码上方没有其他位置将abswhos设置为变量。

对于记录,当您执行builtin=exp(1)时,似乎会发生一些奇怪的特定于版本的弹出错误。大卫指出了这一点。不幸的是,我不能用R2013b 64位重现它。

答案 2 :(得分:1)

好的,如果我运行此代码

a=exp(1)

clear

builtin=exp(1)

我得到了

a =
    2.7183
builtin =
    2.7183

和此错误

enter image description here

但是,如果我运行此代码

a=exp(1)

clear

builtin=exp(1)

clear

a=exp(1)

我没有错误!

这是Mac OSX上的R2012b。