【问题标题】:How to find minimum from an array in Octave?如何从 Octave 中的数组中找到最小值?
【发布时间】:2015-07-07 08:42:35
【问题描述】:

我是 Octave 的初学者! 我正在努力从数组 mse_array 中找出最小值。我不断收到一条错误消息:“下标索引必须是小于 2^31 的正整数或逻辑”

有人可以帮我吗?这是我的代码:

function randomLines(data1, data2)
mse_array = []
A = rand(2,10)*100
 for i = columns(A)
    max = A (1, i) 
    min = A (2, i)
    m = (max-min)/0.16
    p = [m min];
    array_function_values = polyval(p,data2);
    current_mse = mseFunction(data1,array_function_values);
    mse_array(end + 1) = current_mse
 endfor
min_value = min(mse_array)
endfunction

【问题讨论】:

  • 你在哪一行得到错误?
  • 请提供完整的错误信息。另外,请指定mseFunction 是什么以及生成错误的函数randomLines 的示例输入,以便我们自己复制它。

标签: arrays matlab octave minimum


【解决方案1】:

您的代码有几个问题。这里有一些可以帮助您入门。

错误可能发生在这一行:

min_value = min(mse_array)

您使用mse_array 作为min 的索引,但mse_array 中的值可能是错误状态下的有效数组索引。 (我猜测这纯粹是基于变量的名称mse_array,这似乎来自某种形式的均方误差计算。)检查行号和错误消息中的所有其他内容很重要。

另一个问题是你的for 循环只计算一次。 columns 函数将返回 A 的标量列数。因此,您的循环声明相当于:

for i = 10

换句话说,代码只会查看A 的最后一列。您可能想使用:

for i = 1:columns(A)

最后,使用您自己的变量名称覆盖 Octave 中的内置 minmax 函数是一个坏主意。如果您覆盖了内置的min 函数,您将无法再直接使用它,直到您调用clear min(或者,您可以调用builtin,但您应该避免这种情况)。相反,只需选择更好的变量名称。

【讨论】:

  • 这是最重要的“最后”部分。 OP 似乎打算使用min 作为min_value-line 中的函数。
  • @Jonas:可能。 min 函数已经在上面的 for 循环中被重载。无需将此代码的变量名称更改为“工作”。
【解决方案2】:

问:如何在 Octave 中找到数组的最小值?

octave 具有内置的自描述文档,可在遇到疑问时使用

答:总是重新阅读 help mindoc min

octave-3.2.4.exe:1> help min
`min' is a function from the file C:\Octave\3.2.4_gcc-4.4.0\libexec\octave\3.2.4\oct\i686-pc-mingw32\max.oct

 -- Loadable Function:  min (X)
 -- Loadable Function:  min (X, Y)
 -- Loadable Function:  min (X, Y, DIM)
 -- Loadable Function: [W, IW] = min (X)
     For a vector argument, return the minimum value.  For a matrix
     argument, return the minimum value from each column, as a row
     vector, or over the dimension DIM if defined.  For two matrices
     (or a matrix and scalar), return the pair-wise minimum.  Thus,

          min (min (X))

     returns the smallest element of X, and

          min (2:5, pi)
             =>  2.0000  3.0000  3.1416  3.1416
     compares each element of the range `2:5' with `pi', and returns a
     row vector of the minimum values.

     For complex arguments, the magnitude of the elements are used for
     comparison.

     If called with one input and two output arguments, `min' also
     returns the first index of the minimum value(s).  Thus,

          [x, ix] = min ([1, 3, 0, 2, 0])
             =>  x = 0
                 ix = 3

     See also: max, cummin, cummax

将元素重新定义(从而呈现不可用)为保留字只会增加麻烦。尝试使用您自己的命名约定,这不会损害系统的其余部分 - 即 anArrayMinimumVALUEaSmallestVALUE,而不是“杀死” Octave 函数min() 通过创建一个意外命名为“also”的变量min

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2016-02-12
    • 1970-01-01
    • 2021-01-08
    • 2019-11-20
    • 2014-10-23
    • 2014-06-01
    • 2022-01-24
    相关资源
    最近更新 更多