How do I make conditional code more efficient
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Walter Roberson
le 25 Mar 2019
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.
Réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!