File Exchange

## N-D histogram

version 1.0 (2.13 KB) by

Extension to the histc function to count the number of data points on N-D grid.

Updated

HISTCND Histogram count for n dimensional data.
N = HISTCND(X,EDGES), for row vectors X, counts the number of values in
X that fall between the grid defined by the cell array of EDGES, each
of whose element is a vector that contain monotonically non-decreasing
values. N is an N-D array each of whose dimension corresponds to
LENGTH(EDGES{j}) and each element contains a count of data that falls
into the edge.

X is N-by-D matrix representing N data points in D dimensional space.

EDGES must have the same length to the number of columns of X.
Alternatively, EDGES can be a numeric vector which gives a uniform
grid for all dimensions of X.

N(k1,k2,...) will count the vector X(i,:) if for each dimension
j = 1,2,..., EDGES{j}(kj) <= X(i,j) < EDGES{j}(kj+1). The last bin will
count any values of X that match EDGES(end). Values outside the values
in EDGES are not counted. Use -inf and inf in EDGES to include all
non-NaN values.

[N,BIN] = HISTCND(X,EDGES) also returns subscript indices BIN.
BIN is zero for out of range values.

Example:
>> X = randn(100,2); % 100-by-2 row vectors
>> edges = {-2:.4:2,-2:.5:2}; % ranges for each dimension
>> histcnd(X,edges)

ans =

0 0 0 1 1 1 0 0 0
0 1 1 2 1 1 0 0 0
1 0 3 4 0 3 0 0 0
0 1 2 1 3 0 1 0 0
0 3 1 4 2 1 3 1 0
1 1 2 3 3 4 1 0 0
0 1 1 2 1 1 4 0 0
0 1 2 2 2 1 0 0 0
1 2 0 3 2 0 0 1 0
0 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0

Kota Yamaguchi

### Kota Yamaguchi (view profile)

Hi Daniel,

You can use fixed step by manually creating range vector. For example,

edge = {[0,1,2,4,8,16], ...}

If what you need is a certain number of uniform edges in the observed data, you also might want to try linspace or logspace function.

edges = {linspace(min_val, max_val, 12), ...}

All the histnd does is to wrap histc function built in Matlab to allow multiple dimensions. If you need to get count of unique values, you need to use unique function instead:

[Xu, m, n] = unique(X, 'rows'); % this will find unique vectors Xu and corresponding index m.

h = histc(m, unique(m)); % histogram over unique index values

You should check the Matlab documentation of unique, hist, or histc function.

Daniel

### Daniel (view profile)

What is more: can histcnd be applied to each single couple of values of the matrix X? I mean: no range...
This should be even better...

Daniel

### Daniel (view profile)

The function is great!
I just have one question: how can I set the vector 'edges' be a numeric vector which gives a uniform grid for all dimensions of X?
I have a X matrix 744x2 size, and I would need histcnd to calculate frequency for groups of values, let's say, range of 12 values.
I can't use the step method given, because I need a fixed step to work with, but I don't know how to define 'edges'.
Thank you very much.

##### MATLAB Release
MATLAB 7.8 (R2009a)