for loop taking too long to operate

조회 수: 18(최근 30일)
SChow
SChow 2020년 10월 6일
댓글: SChow 2020년 10월 6일
I have a matrices (b1 and popx) with size 25000x50000, code is a vector which contains unique values in b1 (of length 300). For elements in popx which correspond to each unique value of b1, I need the sum of popx,
The below code takes very long (>2 hours) to operate, Any help to lower computation time is much appreciated
for i=1:300
popx1=popx;
popx1(b1~=code(i))=NaN;
popn=nansum(nansum(popx1));
popn1(i)=popn;
end;

채택된 답변

Jos (10584)
Jos (10584) 2020년 10월 6일
Pre-allocation, and recoding using logical indexing and sum should speed things up
popn1 = nan(300,1) ; % pre-allocation
for i=1:300
tf = b1 == code(i) ;
popn1(i) = sum(popx(tf), 'all') ;
end;
  댓글 수: 1
SChow
SChow 2020년 10월 6일
much quicker , thanks

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

추가 답변(0개)

범주

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by