vectorisation a for loop

3 次查看(过去 30 天)
Johnny
Johnny 2019-12-8
评论: Stephen23 2019-12-8
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
Stephen23 2019-12-8
Because you are not concatenating anything, square brackets are not needed here:
dist=log((10:-1:1)+retint);

请先登录,再进行评论。

采纳的回答

David Hill
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);

更多回答(1 个)

Stephen23
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)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by