Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of elements of a given value in a matrix?

Does anyone know how to count the number of times a value appears in a matrix?

For example, if I have a 1500 x 1 matrix M (vector) which stores the values of weekdays (1 - 7), how could I count how many Sundays (1), Mondays(2), ... , Saturdays(7) are stored in M?

like image 269
Niko Gamulin Avatar asked May 21 '10 09:05

Niko Gamulin


People also ask

How do you determine the number of elements in a matrix?

A matrix is said to be of order m x n if it has m rows and n columns. The total number of elements in a matrix is equal to (m*n). So we start from 1 and check one by one if it divides N(the total number of elements).

How do you count the number of elements in a matrix in MATLAB?

n = numel( A ) returns the number of elements, n , in array A , equivalent to prod(size(A)) .

How do you count the number of rows in a matrix?

If for example your matrix is A, you can use : size(A,1) for number of rows. size(A,2) for number of columns. Also there are some other ways like : length ( A(:,1) ) for number of rows.

How do you count a column in a matrix?

Use the [row,column] = size(matrix); to directly obtained the number of columns and rows of our matrix from this code through the size() function.


1 Answers

Have a look at Determine and count unique values of an array.

Or, to count the number of occurrences of 5, simply do

sum(your_matrix == 5) 
like image 141
aioobe Avatar answered Oct 12 '22 15:10

aioobe