Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' ]
like image 604
Learner Avatar asked Jul 16 '26 06:07

Learner


2 Answers

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'
like image 173
abcd Avatar answered Jul 18 '26 21:07

abcd


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'
like image 37
gnovice Avatar answered Jul 18 '26 22:07

gnovice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!