Is there a way to count number of "objects" in a matrix?
3 views (last 30 days)
Show older comments
Alec Gutmanstein
on 4 Feb 2016
Edited: Alec Gutmanstein
on 4 Feb 2016
Let's say I have a 5x5 matrix of 1s with 2s located at (1,1) and (2,4) and (4,5) or any assortment of points. Am I able to "count" the number of 2s in the matrix full of 1s?
Note the 2s location can vary at any point and is not consistent (can clarify if need be)
0 Comments
Accepted Answer
Star Strider
on 4 Feb 2016
You question lacks significant clarity, but you can find the total number of ones or twos or any other integer with:
M = randi([0 2],5); % Matrix Containing {0,1,2}
Ones = sum(M(:) == 1);
Twos = sum(M(:) == 2);
This works because integers can be represented exactly in binary representation. Non-integer values require that you compare the values using a tolerance value, because decimal fractions cannot be exactly represented as binary floating point numbers.
0 Comments
More Answers (0)
See Also
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!