Matrix 将单元格转换为矩阵
我有一个单元格数组,我想把它转换成二维矩阵 我做了以下工作:Matrix 将单元格转换为矩阵,matrix,matlab,Matrix,Matlab,我有一个单元格数组,我想把它转换成二维矩阵 我做了以下工作: 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
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中做到这一点?只需将最后一行更改为:
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
只需将最后一行更改为:
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
这可能更快,因为它避免了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);
这可能更快,因为它避免了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);
我假设
[1,10,9]
是一个输入错误->它返回[1,9,10]
,对吗?我假设[1,10,9]
是一个输入错误->它返回[1,9,10]
,对吗?