【问题标题】:What is an OCTAVE equivalent of MATLAB discretize什么是 MATLAB 离散化的 OCTAVE 等价物
【发布时间】:2022-01-13 15:25:58
【问题描述】:

x=rand(1,10); bins=discretize(x,0:0.25:1);

在 Matlab R2020b 中运行上述行的一个实例会为 x 和 bins 生成以下输出。

x = 0.1576, 0.9706, 0.9572, 0.4854, 0.8003, 0.1419, 0.4218, 0.9157, 0.7922, 0.9595

bins = 1, 4, 4, 2, 4, 1, 2, 4, 4, 4

内置函数 discretize 尚未在 Octave 中实现。如何在 OCTAVE 中实现相同的 bin 值?任何人都可以启发我吗?我使用的是 Octave 6.2.0。

【问题讨论】:

标签: matlab octave


【解决方案1】:

您可以将interp1 与“上一个”选项一起使用:

edges = 0:0.25:1;
x = [0.1576, 0.9706, 0.9572, 0.4854, 0.8003, 0.1419, 0.4218, 0.9157, 0.7922, 0.9595];
bins = interp1 (edges, 1:numel(edges), x, 'previous')

另一个可以使用的函数是lookup

bins = lookup(edges, x);

这里我比较了interp1lookuphistc 的性能,正如Tasos Papastylianou 推荐的那样:

edges = 0:0.025:1;
x = sort (rand(1,1000000));

disp ("-----INTERP1-------")
tic;bins = interp1 (edges, 1:numel(edges), x, 'previous');toc

disp ("-----HISTC-------")
tic;[ ~, bins ] = histc (x, edges);toc

disp ("-----LOOKUP-------")
tic; bins = lookup (edges, x);toc

结果:

-----INTERP1-------
Elapsed time is 0.0593688 seconds.
-----HISTC-------
Elapsed time is 0.0224149 seconds.
-----LOOKUP-------
Elapsed time is 0.0114679 seconds.

【讨论】:

    【解决方案2】:

    tl;博士:

    x = [ 0.1576, 0.9706, 0.9572, 0.4854, 0.8003, 0.1419, 0.4218, 0.9157, 0.7922, 0.9595 ]
    [ ~, Bins ] = histc( x, 0: 0.25: 1 )
    % Bins = 1   4   4   2   4   1   2   4   4   4
    

    说明:

    根据matlab手册:

    早期版本的 MATLAB® 使用 histhistc 函数作为创建直方图和计算直方图 bin 计数的主要方法 [...] 不鼓励在新代码中使用 hist 和 histc [... ] histogramhistcountsdiscretize 是推荐用于新代码的直方图创建和计算函数。

    discretize 的行为类似于 histcounts 函数的行为。使用 histcounts 查找每个 bin 中的元素数。另一方面,使用 discretize 来查找每个元素属于哪个 bin(不计算)。

    Octave 还没有实现discretize,但仍然支持histc,正如上面所暗示的,它做同样的事情,但界面不同。

    根据histc的octave文档

    -- [N, IDX] = histc ( X, EDGES )
     Compute histogram counts.
    
     [...]
    
     When a second output argument is requested an index matrix is also
     returned.  The IDX matrix has the same size as X.  Each element of
     IDX contains the index of the histogram bin in which the
     corresponding element of X was counted.
    

    因此你的问题的答案是

    [ ~, Bins ] = histc( x, 0:0.25:1 )
    

    使用您的示例:

    x = [ 0.1576, 0.9706, 0.9572, 0.4854, 0.8003, 0.1419, 0.4218, 0.9157, 0.7922, 0.9595 ]
    [ ~, Bins ] = histc( x, 0: 0.25: 1 )
    % Bins = 1   4   4   2   4   1   2   4   4   4
    

    PS。如果你喜欢discretize提供的接口,你可以很容易地自己创建这个函数,通过适当地包装histc

    discretize = @(X, EDGES) nthargout( 2, @histc, X, EDGES )
    

    您现在可以像在您的示例中一样直接使用此 discretize 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 2012-07-22
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多