Creating Individual Matrix based on Label Matrix from DataMatrix
Let label be a matrix of size N x 1 (type double) and data be a matrix of size N x M (type double). The entries in the Label matrix looks like 开发者_运维问答[ 1; 23; 135; ....; 6] which conveys that the
First row in the data matrix belongs to label 1
Second row in the data matrix belongs to label 2 and label 3 Third row in the data matrix belongs to label 1, label 3 and label 5 and so onI would like to create a cell array say Individual{i} which stores all those rows from the data matrix which belongs to label i as given by the label matrix.
The resultant Individual{i} matrix will be size N_i x M.
Is there any efficient way to do the thing rather than looping row by row of data and label matrix?
I would turn your matrix label
into a Boolean matrix L:
L = [ 1 0 0 0 0 0 ;
0 1 1 0 0 0 ;
1 0 1 0 1 0 ;
...
0 0 0 0 0 1 ];
for your example. You can use a sparse matrix if N or the number of labels is very large.
Then I think what you call N_i
is sum(L(:, i))
and L' * data
would compute the sum of all the rows in data
with label L
.
What do you want to do with the data
once it's reached the Individual
cell array? There's almost certainly a better way to do it...
Given the correct variables: N, M, data, label
as you described, here's a sample code that creates the desired cell array Individual
:
%# convert labels to binary-encoded format (as suggested by @Tom)
maxLabels = 9; %# maximum label number possible
L = false(N,maxLabels);
for i=1:N
%# extract digits of label
digits = sscanf(num2str(label(i)),'%1d');
%# all digits should be valid label indices
%assert( all(digits>=1) && all(digits<=maxLabels) );
%# mark this row as belong to designated labels
L(i,digits) = true;
end
%# distribute data rows according to labels
individual = cell(maxLabels,1);
for i=1:maxLabels
individual{i} = data(L(:,i),:);
end
精彩评论