MATLAB: How to convert 3D matrix to 1D

matrix

I got a color image and store into a variable A.
A =
(22,10,10) (22,10,10) (39,40,50)
(89,11,14) (23,11,11) (99,10,10)
(89,11,14) (69,10,10) (99,10,10)
x=1 when loop horizontally I wish to register the first color I seem and label it into x.
when loop same color then label it into same label.
when new color is seem then register the color and label into x+1.
I wish to get a table like
color label
(22,10,10) 1
(39,40,50) 2
(89,11,14) 3
(23,11,11) 4
(99,10,10) 5
(69,10,10) 6
so result finally get is
B=
1 1 2
3 4 5
3 6 5
How to get the label table and how to get the result?

Best Answer

The way to do this is to reshape your image into an nx3 matrix where each row correspond to the three colours of a pixel. You can then apply unique with the 'rows' option on this to get your labels. It's then just a matter of reshaping the output.
Note that doing the scanning by rows rather than by columns complicate the code somewhat.
Also, please, post valid matlab code rather than leaving it to us to generate valid matrix
A = cat(3, [22 22 39;89 23 99; 89 69 99], ... it would have been great
[10 10 40; 11 11 10; 11 10 10], ... if I could just have
[10 10 50; 14 11 10; 14 10 10]) %copy/pasted that from your question
[~, ~, labels] = unique(reshape(permute(A, [2 1 3]), [], 3), 'rows', 'stable');
B = reshape(labels, size(A, 2), size(A, 1))'
The same code if you do the labeling by column:
[~, ~, labels] = unique(reshape(A, [], 3), 'rows', 'stable'); %no need to transpose anymore
B = reshape(labels, size(A, 1), size(A, 2)) %no need to transpose either.