필터 지우기
필터 지우기

Sum up values in a certain range with logical indexing (better performance)

조회 수: 1 (최근 30일)
buhmatlab
buhmatlab 2020년 6월 7일
편집: Stephen23 2020년 6월 7일
Hi,
Since my script runs very slowly, I try to optimize the code and wonder if anybody is able help?
The (old and slow) code does the following:
In each row, the sum of all values from rows, that feature the name of the corresonding row and appear before the EventDate of the corresponding row, is calulated.
csum = zeros(size(values));
for i=1:length(values)
csum(i) = sum(values(find(Name==Name(i) & EventDate < EventDate(i))));
end
Later on, my project also requires to calculate the sum of other ranges, so for example not all values of EventDate < EventDate(i) and Name==Name(i)but only the last two values of rows row where EventDate < EventDate(i) and Name==Name(i), another example would only focus on the last value which would not need to calculate the sum at all since it is only one value.
In this case I would adjust the code:
sum(values(find(Name==Name(i) & EventDate<EventDate(i) ,n,'last')));
However, I wonder if there is any way to improve the code by avoiding loops and using for example logical indexing. The performance of the current code is by far not good enough.
Thank you so much!
  댓글 수: 1
Stephen23
Stephen23 2020년 6월 7일
편집: Stephen23 2020년 6월 7일
For the first example you can get rid of find . But for the second example, there might not be a simple alternative.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by