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!