x=rand(1,10); bins=discretize(x,0:0.25:1);
在 Matlab R2020b 中運行上述行的實體為 x 和 bin 生成以下輸出。
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
Octave 中尚未實作內置函式discretize。如何在 OCTAVE 中實作相同的 bin 值?任何人都可以啟發我嗎?我正在使用 Octave 6.2.0。
uj5u.com熱心網友回復:
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? 使用
hist和histc函式作為創建直方圖和計算直方圖 bin 計數的主要方式 [...] 不鼓勵在新代碼中使用 hist 和 histc [...]histogram,histcounts,并且discretize是推薦的直方圖創建和新代碼的計算功能。
和
discretize 的行為類似于 histcounts 函式的行為。使用 histcounts 查找每個 bin 中的元素數。另一方面,使用 discretize 查找每個元素屬于哪個 bin(不計算)。
Octave 還沒有實作discretize,但仍然支持histc,正如上面所暗示的,它做同樣的事情,但具有不同的介面。
根據八度檔案 histc
-- [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
附注。如果您喜歡 提供的介面discretize,您可以通過histc適當的包裝輕松地自己創建此函式:
discretize = @(X, EDGES) nthargout( 2, @histc, X, EDGES )
您現在discretize可以像示例中一樣直接使用此函式。
uj5u.com熱心網友回復:
您可以將interp1與 'previous' 選項一起使用:
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);
在這里,我比較了 的性能interp1,lookup也是 Tasos Papastylianouhistc推薦的:
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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/379347.html
