科学计数法的 Matlab 输出 [错误:下标索引必须是实数正整数或逻辑数。]

计算科学 矩阵 matlab 精确
2021-12-25 22:06:09

我有矩阵形式的 X、Y 和 Z 变量,每个变量的大小为 nx 1。例如:

X = [-38.0400, -38.6700, -38.9300, -39.4500...]

每当我运行以下代码时:

% find center of X
minx = find(X==min(min(X)));
maxx = find(X==max(max(X)));
centx = (minx + maxx) / 2;
xy = Y(centx);
xz = Z(centx);
centx = [centx xy xz];

我会得到最初的答案,例如:

centx = 6.6034e+04

但随后会显示错误:

Subscript indices must either be real positive integers or logicals.
Error in max_point(line 5)
xy = Y(centx);

我的问题是

  • 由于原始条目中的尾随零,答案是否以科学记数法(指数形式)给出?
  • 我怎样才能避免以科学记数法(指数形式)得到答案(因为我认为这是错误的原因)?

提前致谢

3个回答

问题就在这里,

centx = (minx + maxx) / 2;

您正在使用浮点数作为数组的索引。错误只是说索引必须是整数。

您想知道哪个索引是 x 范围的中心吗?您将需要以不同的方式做到这一点。这个怎么样,

% find center of X
minx = find(X==min(min(X)));
maxx = find(X==max(max(X)));
centx = uint32(round((minx + maxx) / 2)); % notice I used the round function here and the cast to make it an integer!
xy = Y(centx);
xz = Z(centx);
centx = [centx xy xz];

这使用了轮函数, http://www.mathworks.com/help/matlab/ref/round.html

round函数会自动使用最合适的整数舍入函数来让您得到最接近的值,我认为这是您在这种情况下想要的。您仍然需要转换为整数,如下所述。

如果小数部分为小数部分 {2} ,则在内部round应用该函数ceil>=12floor<12

指数答案只是因为这是 MATLAB 打印浮点数的方式。

centx = (minx + maxx) / 2; 正如@boyfarrell 指出的那样,将导致非整数数组索引。如果这是您正在寻找的,您可以使用函数ceil或获取最近的整数索引。floor

默认情况下,在 matlab 中,所有内容都是双精度浮点数矩阵。如果您喜欢使用整数变量进行索引运算,您可以使用http://www.mathworks.it/it/help/matlab/numeric-types.html中列出的转换函数执行显式类型转换例如

minx = uint32(find(X==min(min(X))));

(这里我使用 32 位无符号整数,假设您不需要 64 位指针。)

注意

>> a = 3/2
a =
    1.5000
>> b = uint32(3)/2 
b =
           2
>> whos
  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double              
  b         1x1                 4  uint32              

或者,您可以按照其他答案中的建议,在 double 中进行索引算术,然后使用ceilandfloor函数对浮点数进行舍入。(请注意ceilfloor返回一个双精度,它们不会转换为整数类型。)