How do I make conditional code more efficient

I currently have a section of a function that is very slow (when length(data) >> 200). I've been struggling to make use of matlab's speedy matrix manipulation, particularly with the conditional statement that has a variable in the condition (u).
data = cumsum(randi(20,1,200)); % An ordered vector of data with no repetitions
t0 = data(end);
tau = 5; % Some arbitrary num
r = zeros(1,50)
for k = 0:49
uvec = data(data<= t0 - k*tau - tau); % All data that meets a condition
inner_int = zeros(1,length(uvec));
for i = 1:length(uvec)
u = uvec(i);
inner_int(i) = sum(data > (k*tau + u) & data <= (k*tau + u + tau) ); % Conditional statement
end
r(k+1) = sum(inner_int);
end
I've been tried various solutions including bsxfun, histcounts and using integrals of matlab's dirac function to reduce my number of for loops, but cannot seem to get anything faster than the above.
For reference this is the maths of what I'm implementing

2 Comments

In that context, where you have sum() of the result of logical expressions, then you are asking to count the number of items that match. In that context, nnz() should be faster than sum()
However, it looks to me as if that formula might be using dirac delta, which corresponds to equality tests rather than inequality tests.
nnz() seems a little faster, thank you! My main issue is the for loops though.
Yes the formula is using dirac delta, so the inner integral is essentially "How many points in the data are between ktau+u and (k+1)tau+u" and the outer integral is 1 if u is in data (and u < the upper bound). It's similar to binning, but again I'm not really sure how to implement it efficiently

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 25 Mar 2019

Edited:

on 25 Mar 2019

Community Treasure Hunt

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

Start Hunting!