Extract unique elements from each row of the matrix (Matlab)

I would like to apply a function that is unique to each row of a given matrix, without involving any loops. Suppose I have the following 4-by-5-matrix

full(A) = [0 1 0 0 1 2 1 0 3 0 1 2 0 0 2 0 3 1 0 0] 

where A is the corresponding sparse matrix. As an example using a for loop, I can do

 uniq = cell(4,1); for i = 1:4 uniq{i} = unique(A(i,:)); end 

and I would get the uniq cell structure given

 uniq{1} = {1} uniq{2} = {[1 2 3]} uniq{3} = {[1 2]} uniq{4} = {[1 3]} 

Is there a faster way to vectorize and avoid loops? I need to apply this to M-by-5 โ€‹โ€‹matrices with M large. Note that I am not interested in the number of unique elements in a row (I know there are answers around such a problem).

+5
source share
2 answers

You can use accumarray with a special function:

 A = sparse([0 1 0 0 1; 2 1 0 3 0; 1 2 0 0 2; 0 3 1 0 0]); % data [ii, ~, vv] = find(A); uniq = accumarray(ii(:), vv(:), [], @(x){unique(x.')}); 

This gives:

 >> celldisp(uniq) uniq{1} = 1 uniq{2} = 1 2 3 uniq{3} = 1 2 uniq{4} = 1 3 
+4
source

you can use num2cell(A,2) to convert each row into a cell, and then cellfun with unique to get an array of cells from unique values โ€‹โ€‹from each row:

 % generate large nX5 matrix n = 5000; A = randi(5,n,5); % convert each row into cell C = num2cell(A,2); % take unique values from each cell U = cellfun(@unique,C,'UniformOutput',0); 
+2
source

All Articles