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.
Author by
Alfred Zhong
Updated on June 13, 2020Comments
-
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)
, thenA
is an1D array
, andhist(A)
can do the histogram.However, what if
A=rand(100,100)
, and I would like to make a histogram on elements ofA
, just like treating each element inA
as an element on a1D array
. Is there a easy way to do so? -
abcd about 13 years
A(:)
as in Jonas' answer does the same as the long reshape command. -
abcd about 13 yearsI like MATLAB's simple column vectorization,
A(:)
because it always seems like the array is smiling, whichever direction you look at it :) -
Alfred Zhong about 13 yearsThank a lot, Jonas! That's exactly what I am looking for
-
Jonas about 13 years@Alfred: If you found my answer helpful, please consider accepting it.