Search code examples
matlabmatrixmatrix-indexing

Creating Label vector using Indicator Matrix in Matlab


Given a binary matrix M of size n x k, i would like to create a vector Label of size n x 1 such that entry of Label should contain the concatenated column index of M where its values are 1

for eg: If the M Matrix is given as

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

The resultant Label Vector should be

 V = [ '34'  
        '4'  
       '14'  
        '0'
      '123' ]

Solution

  • Here is one way to do it compactly and in a vectorized manner.

    [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'