Matlab

How to Count Number of Specific Values in Matrix in MATLAB

MATLAB stands for matrix laboratory, which allows us to perform various matrix operations. One such operation is counting the count of specific matrix elements. MATLAB does not include any built-in function to directly perform this operation; however, we can perform this operation using relational operators and the sum() function.

Follow this article to learn how to count specific matrix elements.

How to Count Specific Elements in a Matrix?

When we deal with very large matrices having a size 1000-by1000 or greater, it becomes very difficult to count the number of specific values manually. Also, when we create matrices using built-in functions like rand, and magic(), we do not know what values these matrices include. To find some specific values in a matrix we can apply relational operators like, <,>, ==, and !=. After that, we can count the values by using MATLAB’s built-in function sum().

Examples

Follow the given examples to learn how to count some specific values in a matrix in MATLAB.

Example 1: How to Count Specific Elements in an 8×8 Matrix?

In the given example, we create a matrix of size 8 using the magic() function. After that, we find the elements in the matrix x that are less than 10. We find the count of specified values using the sum() function.

x = magic(8)

count = sum(x<10,'all')

 

Example 2: How to Count Specific Elements in a 1000×1000 Matrix

The given MATLAB code creates a diagonal matrix of size 1000 using the eye() function. After that, it finds the elements in the matrix x that are equal to 1. We find the count of specified values using the sum() function.

x =eye(1000);

count = sum(x==1,'all')

Conclusion

You can easily count the number of specific values in a matrix in MATLAB using the sum() function with relational operators. For the sum() function to work, you must specify the arguments appropriately to create a logical mask that identifies the elements satisfying the desired condition. This guide has provided an easy and quick way to count specific values in the matrix in MATLAB, helping you to use the desired method on your own created matrix.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.