How do I make conditional code more efficient

7 次查看(过去 30 天)
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 个评论
Walter Roberson
Walter Roberson 2019-3-25
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.
William Green
William Green 2019-3-25
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

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by