这也是(被低估的)accumarray的机会
A= [ 1 1 0 2 2 2 2 0 0 3 3 0 0;
0 1 1 0 0 2 2 2 2 3 3 0 0 ];
N = size(A,2);
result = zeros(max(A(:)),N);
for ii=1:N
s = accumarray(nonzeros(A(:,ii)),1);
result(1:numel(s),ii) = s;
end
太糟糕了,只有 accumarray 不能一次性完成所有操作:(
编辑
一次 accumarray 调用就搞定了::p
A= [ 1 1 0 2 2 2 2 0 0 3 3 0 0;
0 1 1 0 0 2 2 2 2 3 3 0 0 ];
N = size(A);
C = repmat(1:N(2),N(1),1);
result = accumarray([A(:)+1 C(:)], 1);
result = result(2:end,:)
编辑2
如果您有一个 3 维输入矩阵,最简单的方法是先将其转换为 2 维矩阵,然后使用上述方法对其进行处理。以下代码执行此转换:
% example data:
A3d = repmat(A,[1 1 2])
A2d = reshape(permute(A3d,[1 3 2]),[],size(A3d,2))
结果:
A3d(:,:,1) =
1 1 0 2 2 2 2 0 0 3 3 0 0
0 1 1 0 0 2 2 2 2 3 3 0 0
A3d(:,:,2) =
1 1 0 2 2 2 2 0 0 3 3 0 0
0 1 1 0 0 2 2 2 2 3 3 0 0
A2d =
1 1 0 2 2 2 2 0 0 3 3 0 0
0 1 1 0 0 2 2 2 2 3 3 0 0
1 1 0 2 2 2 2 0 0 3 3 0 0
0 1 1 0 0 2 2 2 2 3 3 0 0