简体   繁体   English

索引超出矩阵尺寸弹出错误

[英]Index exceeds matrix dimensions popup error

I am trying to do an approximation of 1/e 我正在尝试近似1 / e

I keep getting an error saying index exceeds matrix dimensions. 我不断收到错误消息,说索引超出了矩阵尺寸。 Why? 为什么?

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)

EDIT 编辑

This answer doesn't really solve the user's problem. 这个答案并不能真正解决用户的问题。 But since what the user wanted was a loop to approximate 1/e, here are some possibilities: 但是由于用户想要的是一个近似1 / e的循环,因此有一些可能性:

One quick approach: 一种快速方法:

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.

A better approach is the dichotomic search: 更好的方法是二分法搜索:

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]

Just for the fun of it. 就是图个好玩儿。

Type whos and make sure abs and exp aren't listed. 输入whos并确保没有列出absexp If they are listed as variables, clear them with: 如果它们被列为变量,请使用以下命令清除它们:

clear abs whos

Then make sure there is no where else above this code that sets abs and whos as variables. 然后确保此代码上方没有其他地方将abswhos为变量。

For the record, it seems there is some strange version-specific popup error that happens when you do builtin=exp(1) . 作为记录,似乎在执行builtin=exp(1)时会发生一些奇怪的特定于版本的弹出错误。 David pointed this out. 大卫指出了这一点。 Unfortunately, I can't reproduce it with R2013b 64-bit. 不幸的是,我无法使用64位R2013b复制它。

OK so if I run this code 好的,所以如果我运行这段代码

a=exp(1)

clear

builtin=exp(1)

I get 我懂了

a =
    2.7183
builtin =
    2.7183

and this error 和这个错误

在此处输入图片说明

However if I run this code 但是,如果我运行此代码

a=exp(1)

clear

builtin=exp(1)

clear

a=exp(1)

I get no error! 我没有错!

This is R2012b on Mac OSX. 这是Mac OSX上的R2012b。

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

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