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' ]
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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With