MATLAB: Create a matrix on the basis of other matrix

MATLAB

Hi given a matrix
M= [ 0 4 8 6;
0 0 0 6;
0 0 0 6;
2 0 0 0;
0 0 0 0;
0 0 0 1;
0 4 7 0;
5 3 0 0;
0 0 0 6;
0 0 0 6;];
I want to create a new matrix A that contain just the diversity, no matter of the order and with no zeros.
so in this case
A = [2 4 8 6;
5 3 7 1];
Someone can help me with the code?

Best Answer

Under the assumption that the "diversity" contains the same number of entries each row
for i = 1:size(M,2)
b(:,i) = unique(nonzeros(M(:,i)));
end
If each column can have different number of interest
b = arrayfun(@(i)unique(nonzeros(M(:,i))),1:size(M,2),'UniformOutput',false)
then you can access to the unique values of the jth row as
b{j}