MATLAB: How to find indeces of values in a matrix which are placed next to each other? And make operation on them as independent groups

findgroupmatrices

I am working on a matrix A (see below) of 0s and 1s, with much larger size. As you can see the ones form 3 groups of different size.
A = [1 1 1 0 0 0 0 0 0 0 0 0;
1 1 1 0 0 0 1 1 1 1 0 0;
1 1 1 0 0 0 1 1 1 1 0 0;
0 0 0 0 0 0 1 1 1 1 0 0;
0 0 0 1 1 0 0 0 0 0 0 0;
0 0 0 1 1 1 1 0 0 0 0 0;
0 0 0 1 1 1 1 0 0 0 0 0];
I would like to be able to find values which correspond to a specific value (1 in this case) and "group" them. Then perform a different operation on each group. The function find(A == 1) unfortunately returns the list of ALL values ==1.
For example I would like each group to assume a different value
A = [4 4 4 0 0 0 0 0 0 0 0 0;
4 4 4 0 0 0 2 2 2 2 0 0;
4 4 4 0 0 0 2 2 2 2 0 0;
0 0 0 0 0 0 2 2 2 2 0 0;
0 0 0 3 3 0 0 0 0 0 0 0;
0 0 0 3 3 3 3 0 0 0 0 0;
0 0 0 3 3 3 3 0 0 0 0 0];
Thank you!

Best Answer

The simplest way to get from that to your second A is to use bwlabel from the image processing toolbox.
newA = bwlabel(A)
Related Question