How to speed up the "unique" function when sorting out unique columns

3 views (last 30 days)
As you can see by running the example code below, the time it takes to compute the number of unique columns quickly deteriorates with matrix size.
Others have proposed ways to write inline code in order to speed this up, but those solutions do not seem to cover column-wise (alt. row-wise) uniqueness.
Please help.
clear all, close all
n = 20; % #objects
% compute all possible combinations of 0 and 1 (#combinations = 2^n)
% 0 - object is turned off
% 1 - object is active
% furthermore, as an example the states 01 and 10 are assumed to be equivalent since order is not an issue
combs = [0 1];
for i = 2:n
combs = combvec(combs,[0 1]);
combsSort = sort(combs, 1); % sort columnwise
tic
uniqueCombs = unique(combsSort.','rows').'; % find unique columns by transposing twice
toc
size(uniqueCombs)
end
  1 Comment
FirefoxMetzger
FirefoxMetzger on 15 Aug 2016
This entire sorting can be solved by:
result = ones(N,N);
result = fliplr(tril(result));
To suggest a better algorithm (if still needed) please be more specific about what you want. The unique() command is the most efficient way to solve a general problem. However, there is often a more efficient implementation depending on the need.

Sign in to comment.

Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!