KrunalParmar
KrunalParmar

Reputation: 1114

Faster version of length(find()) for selecting elements from some range from vectors (MATLAB)

I have 1Xn cell array of values. and I want to count values that are in given range in matlab. I implemented it as follows :

count1 = length(find(h{1}<ti & h{1}>ti-INT));

h is my cell array and I want the count of values between ti and ti-INT.

This implementation give correct result, but it is very slow. Is there any faster function available for the specified operation ?

Upvotes: 0

Views: 176

Answers (1)

user2271770
user2271770

Reputation:

Sum the occurrence flags:

 count1 = sum(h{1}<ti & h{1}>ti-INT);

I know that I will upset the Gods of MATLAB for using tic and toc for code timig, but:

x = rand(10^7,1);
tic; sum(x>0.5); toc;
tic; nnz(x>0.5); toc;
tic; length(find(x>0.5)); toc;

shows on several runs that sum() is twice as fast as nnz(), and 3 times faster than length(find()), e.g.:

Elapsed time is 0.049855 seconds.
Elapsed time is 0.120931 seconds.
Elapsed time is 0.162025 seconds.

This is on my R2012a running on a Windows machine with i5 + 3Gb RAM.

Later edit:

For counting the elements from the entire cell array, one may use:

count_all = sum(cellfun(@(x) sum(x<ti & x>ti-INT), h));

Upvotes: 4

Related Questions