Histogram on elements of a 2D matrix in Matlab

26,425

Solution 1

You just have to reshape A into a vector, then you can use hist as usual:

hist(A(:))

Solution 2

This command will do what you want:

hist(reshape(A, prod(size(A)), 1))

What it does is create a vector out of the matrix A by reshaping it into a matrix with one column and a number of rows equal to the number of elements of A:

prod(size(A)) = number_of_columns(A) * number_of_rows(A)

Or the short way:

hist(A(:))

This takes every element of A in sequence and thus also generates a vector.

Share:
26,425
Alfred Zhong
Author by

Alfred Zhong

Updated on June 13, 2020

Comments

  • Alfred Zhong
    Alfred Zhong almost 4 years

    I am wondering if there is any build in function or an easy way to plot a histogram of elements of a 2d array.

    For example, if A=rand(100,1), then A is an 1D array, and hist(A) can do the histogram.

    However, what if A=rand(100,100), and I would like to make a histogram on elements of A, just like treating each element in A as an element on a 1D array. Is there a easy way to do so?

  • abcd
    abcd about 13 years
    A(:) as in Jonas' answer does the same as the long reshape command.
  • abcd
    abcd about 13 years
    I like MATLAB's simple column vectorization, A(:) because it always seems like the array is smiling, whichever direction you look at it :)
  • Alfred Zhong
    Alfred Zhong about 13 years
    Thank a lot, Jonas! That's exactly what I am looking for
  • Jonas
    Jonas about 13 years
    @Alfred: If you found my answer helpful, please consider accepting it.