2011-05-27 87 views
3

给定一个二进制矩阵中号大小N×K个的标签载体,我想创建矢量大小为nx 1使得标签的条目应包含的标签级联列指数M其中其值是1 创建在Matlab使用指标矩阵

为例如:如果中号矩阵给定为

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

所得标签矢量应该是

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

回答

4

下面是一种简洁和矢量化的方法。

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

可以使用find函数或循环来构建串(精加工后,用“0”替换空数组索引)。

2

下面是使用FINDACCUMARRAY一个解决方案,返回字符串的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'