Unique elements in each column of an array (Matlab) -


i might bit rusty matlab, maybe answer question more trivial imagine @ moment. have searched online efficient solutions , haven't found any, try here.

i have large matrix, y here:

n = 1e6; k = 20; n = 100; y = ceil(n * rand(k, n)); 

for each column of array count number of unique elements. loop slow:

tic r = zeros(n, 1); ii = 1:n   r(ii) = numel(unique(y(:, ii))); end toc 

looking vectorised, faster version.


david's answer seems correct , fast too. thank you!

n = 1e6; k = 20; n = 100; y = ceil(n * rand(k, n));  tic r1 = zeros(n, 1); ii = 1:n   r1(ii) = numel(unique(y(:, ii))); end toc  tic r2 = sum(diff(sort(y)) ~= 0) + 1; toc  all(r1' == r2) 

try this

sum(diff(sort(y))~=0)+1 

which uses functions vectorise. performance seems better for loop case, i'd imagine larger problems proposed solution worse due memory limitation.

with n=1e5, method takes ~7.5s on computer, , proposal takes ~0.05s. n=1e6, timings ~75s , ~0.75s.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -