vectorisation a for loop
조회 수: 1 (최근 30일)
이전 댓글 표시
c=5;
retint=0;
dist=log([10:-1:1]+retint);
for i=1:length(dist)
eta=exp(-c*abs(dist(i)-dist));
discrim(i)=1/sum(eta);
end
Does anyone know how to vectorise this for loop to make it more efficient?
댓글 수: 1
Stephen23
2019년 12월 8일
Because you are not concatenating anything, square brackets are not needed here:
dist=log((10:-1:1)+retint);
채택된 답변
David Hill
2019년 12월 8일
Although arrayfun is really a loop,
c=5;
retint=0;
dist=log([10:-1:1]+retint);
discrim=arrayfun(@(x)1/sum(exp(-c*abs(dist-x))),dist);
댓글 수: 0
추가 답변 (1개)
Stephen23
2019년 12월 8일
Real vectorized code (no loop or arrayfun):
eta = exp(-c*abs(bsxfun(@minus,dist,dist(:))));
discrim = 1./sum(eta,1)
Or for MATLAB versions >=R2016b:
eta = exp(-c*abs(dist-dist(:)));
discrim2 = 1./sum(eta,1)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!