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
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.
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!