簡體   English   中英

在MATLAB中沿一維直方圖

[英]Histogram along one dimension in MATLAB

假設我有一個N×M矩陣A 我想計算A每一列的直方圖。 天真的方法是做這樣的事情:

edges = 0:5:100;
counts = zeros(numel(edges) - 1, M);
for i_c = 1:M
  counts(:, i_c) = histcounts(A(:, i_c), edges);
end

有沒有更好(更快)的方法?

編輯:添加一些性能測試

好的,讓我們做一些測試。 第一histcounts +循環,然后使用替代arrayfun和索引向量,然后btmcnellis / randomGuy的溶液與cellfun ,終於obchardon '使用氏溶液histc 似乎對於長列, histcount更有效。 但是對於較短但很多的列, histc大獲全勝!

niter = 10;

M = 100;
N = 10000;

A = rand(M, N);
edges = 0:.05:1;


counts1 = zeros(numel(edges) - 1, N);
counts2 = zeros(numel(edges) - 1, N);
counts3 = zeros(numel(edges) - 1, N);
counts4 = zeros(numel(edges), N);

tic;
for i_r = 1:niter
    for i_c = 1:N
        counts1(:, i_c) = histcounts(A(:, i_c), edges);
    end
end
toc

tic;
for i_r = 1:niter
    counts2 = cell2mat(arrayfun(@(ind) histcounts(A(:, ind), edges), 1:size(A, 2), 'UniformOutput', 0)')';
end
toc

tic;
for i_r = 1:niter
    Acell = num2cell(A, 1);
    counts3 = cell2mat(cellfun(@(column) histcounts(column, edges), Acell, 'UniformOutput', 0)')';
end
toc

tic;
for i_r = 1:niter
    counts4 = histc(A, edges, 1);
end
toc

all(counts1(:) == counts2(:))
all(counts1(:) == counts3(:))
counts4 = counts4(1:numel(edges)-1, :); % histc has an extra bin
all(counts1(:) == counts4(:))

實際測試:

niter = 100; 
M = 10000;
N = 100;

經過的時間是2.423785秒。
經過的時間是2.730303秒。
經過的時間是3.774217秒。
經過的時間是2.721766秒。

niter = 10;
M = 100;
N = 10000;

經過的時間是5.438335秒。
經過的時間是7.387587秒。
經過的時間是7.647818秒。
經過的時間是0.276491秒。

您可以使用: histc

x = [0:5:100];
y = histc(A,x, dim); 

其中dim是要計算的維度。

接着

hist(y(:,1),x);
hist(y(:,2),x);
...

將數組A拆分為一個單元格數組,其中每個單元格都是矩陣中的單個列:

Acell = [mat2cell(A',ones(1,M))]';

將使用cellfun的功能cellfun單元格數組Acell每個單元格

counts = cellfun(@(x)histcounts(x,edges),Acell);

counts將是一個單元格數組,每個單元格包含來自A的相應列的歷史記錄。

您可以使用num2cellcellfun ,盡管我不知道這與幼稚的方法在性能方面的比較。

默認情況下, num2cell接受一個矩陣並將其轉換為一個單元格數組,其中每個單元格都包含矩陣的一個元素,但是傳遞第二個參數允許您沿特定維度進行操作。 因此,對於2x3矩陣Anum2cell(A, 1)將返回1x3單元格數組,其中每個單元格包含A的2×1列。

cellfun將函數應用於單元格的每個元素。 因此,在這種情況下,您可以像上面那樣從num2cell獲取一個單元格數組C輸出, num2cell應用於A每一列,如下所示:

counts = cellfun(@(column) histcounts(column, edges), C);

counts應該是一個3元素的數組,其中第i個元素包含A的第i個列的歷史histcounts結果。

(請注意,上面的@()語法是一個匿名函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM