3

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' ]
gnovice
  • 125,304
  • 15
  • 256
  • 359
Learner
  • 962
  • 4
  • 15
  • 30

3 Answers3

4

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'
abcd
  • 41,765
  • 7
  • 81
  • 98
2

Here's a solution using FIND and ACCUMARRAY that returns an N-by-1 cell arrays of strings:

>> [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'
gnovice
  • 125,304
  • 15
  • 256
  • 359
1

You can use the find function or loop to build the strings (replacing empty array indices with '0' after finishing).

mut1na
  • 795
  • 6
  • 21