2014-05-03 107 views
1

我已经单元的阵列我希望它被转换成2D小区转换到矩阵

的矩阵我做了以下:

B = [9 8 8 8 10 10 10 10 9 9]; 
A = [8,9,10]; 
Y = arrayfun(@(x) find(B==x),unique(A),'Un',0); 

结果是:

Y = {[2,3,4] , [1,10,9] , [5,6,7,8] } 

现在我想Y是这样的:

Y = 2 3 4 0 0 0 0 0 0 0 
    1 10 9 0 0 0 0 0 0 0 
    5 6 7 8 0 0 0 0 0 0 

有尺寸为A的行和尺寸为B的列的2D矩阵,我如何在MATLAB中做到这一点?

+2

我假定'[1,10,9]'是一个错字 - >它返回'[1,9,10]' ,对吗? – thewaywewalk

回答

4

你的最后一行就变为:

Y = cell2mat(arrayfun(@(x) [find(B==x) 0*find(B~=x)],unique(A),'Uni',0).') 

也包括不通过的情况,并将其设置为零的所有值。然后所有单元格的大小相同,您可以使用cell2mat

Y = 

    2  3  4  0  0  0  0  0  0  0 
    1  9 10  0  0  0  0  0  0  0 
    5  6  7  8  0  0  0  0  0  0 
+0

谢谢你完美的工作:) – TravellingSalesWoman

0

这可能更快,因为它避免了cellfun

Y = bsxfun(@eq, unique(A).', B); %'// compare elements from A and B 
Y = bsxfun(@times, Y, 1:size(Y,2)); %// transform each 1 into its row index 
[~, ind] = sort(~Y, 2); %// this will move zeros to the right 
ind = bsxfun(@plus, (ind-1)*size(Y,1), (1:size(Y,1)).'); %'// make linear index 
Y = Y(ind);