Skip to content

Instantly share code, notes, and snippets.

@tonyfast
Created April 16, 2014 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyfast/10795304 to your computer and use it in GitHub Desktop.
Save tonyfast/10795304 to your computer and use it in GitHub Desktop.
A Masked N-D array containing only the first M lowest values
%% A code to find the N highest or lowest values in a N-D array without using sort.
N = [10 10 10];
% nbins is an approximate
% higher values improve accuracy but lower efficiency
nbins = 101;
chopto = 100; % Chop to the first hundred values approximately
A = rand( N );
[y,x] = hist(A(:), nbins);
%% the index to chop
id = find( cumsum(y) >= chopto, 1, 'first' );
%% logical array into the lower values
b = A < x(id);
disp(sprintf( 'The number of nonzero values is %i.', nnz(b)) );
%% The new masked array is
A(~b) = 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment