Creating label vector using indicator matrix in Matlab

Given a binary matrix M of size nxk , I would like to create a Label vector of size nx 1 strong> so that the Label record must contain the index of the concatenated column M , where its values ​​are 1

for example: If the matrix M is given as

M = [ 0 0 1 1  
      0 0 0 1  
      1 0 0 1
      0 0 0 0
      1 1 1 0 ]

Label result should be

 V = [ '34'  
        '4'  
       '14'  
        '0'
      '123' ]
+3
source share
3 answers

Here is one way to do it compactly and in vector form.

[nRows,nCols]=size(M);
colIndex=sprintf('%u',0:nCols);

V=arrayfun(@(x)colIndex(logical([~any(M(x,:)) M(x,:)])),1:nRows,'UniformOutput',false)

V = 

    '34'    '4'    '14'    '0'    '123'
+4
source

FIND ACCUMARRAY, N--1 :

>> [r,c] = find(M);  %# Find the row and column indices of the ones
>> V = accumarray(r,c,[],@(x) {char(sort(x)+48).'});  %'# Accumulate and convert
                                                       %#   to characters
>> V(cellfun('isempty',V)) = {'0'}  %# Fill empty cells with zeroes

V = 

    '34'
    '4'
    '14'
    '0'
    '123'
+2

You can use the find function or a loop to construct strings (replacing the empty array indices with "0" after completion).

+1
source

All Articles