Faster way to create a matrix of the unique() of each row of a matrix
10 views (last 30 days)
Let A be a matrix of relatively big size(A,1), say 2000, and relatively small size(A,2), say 20. I am looking for a faster way to construct a matrix B such that the i-th row of B consists of unique(B(i,:)), padded appropriately, say with 0-s, so that all these rows have the same length (in order to fit together as the matrix B).
I am currently using the following code:
[n,m] = size(A); % A is, say, a non-zero uint8 matrix
A = A.'; % it's better to work with columns in MATLAB?
B = zeros(m,n,'uint8');
t = 0; % will truncate B at t;
for i=1:n % loop through the columns of A.'
col = unique(A(:,i));
s = length(col);
B(1:s,i) = col;
t = max(t,s);
B = B.'; % go back to the original form
B = B(:,1:t);
When size(A,1) is big, the long loop is perhaps suboptimal. Moreover, A and B are actually GPU arrays, so the code is supposed to run on the GPU. So is there perhaps a faster/smarter (vectorized) way to do this?