fast 2dimensional histograming in matlab

前端 未结 2 685
北恋
北恋 2020-11-30 09:32

I have written a 2D histogram algorithm for 2 matlab vectors. Unfortunately, I cannot figure out how to vectorize it, and it is about an order of magnitude too slow for my

相关标签:
2条回答
  • 2020-11-30 09:51

    Here is my version for a 2D histogram:

    %# some random data
    X = randn(2500,1);
    Y = randn(2500,1)*2;
    
    %# bin centers (integers)
    xbins = floor(min(X)):1:ceil(max(X));
    ybins = floor(min(Y)):1:ceil(max(Y));
    xNumBins = numel(xbins); yNumBins = numel(ybins);
    
    %# map X/Y values to bin indices
    Xi = round( interp1(xbins, 1:xNumBins, X, 'linear', 'extrap') );
    Yi = round( interp1(ybins, 1:yNumBins, Y, 'linear', 'extrap') );
    
    %# limit indices to the range [1,numBins]
    Xi = max( min(Xi,xNumBins), 1);
    Yi = max( min(Yi,yNumBins), 1);
    
    %# count number of elements in each bin
    H = accumarray([Yi(:) Xi(:)], 1, [yNumBins xNumBins]);
    
    %# plot 2D histogram
    imagesc(xbins, ybins, H), axis on %# axis image
    colormap hot; colorbar
    hold on, plot(X, Y, 'b.', 'MarkerSize',1), hold off
    

    hist2d

    Note that I removed the "non-negative" restriction, but kept integer bin centers (this could be easily changed into dividing range into equally-sized specified number of bins instead "fractions").

    This was mainly inspired by @SteveEddins blog post.

    0 讨论(0)
  • 2020-11-30 10:10

    You could do something like:

    max0 = max(fvec0) + 1;
    max1 = max(fvec1) + 1;
    
    % Combine the vectors
    combined = fvec0 + fvec1 * max0;
    
    % Generate a 1D histogram
    hist_1d = hist(combined, max0*max1);
    
    % Convert back to a 2D histogram
    hist_2d = reshape(hist, [max0 max1]);
    

    (Note: untested)

    0 讨论(0)
提交回复
热议问题