performance - Eigen matrix/array compute distances efficiently -
i need create eigen array distances between each source , recorder position.
i have 3 eigen::array sx, sy , sz denoting source positions , 3 eigen::array rx, ry , rz denoting recorder positions. length of source , recording position arrays not necessary same.
using for-loops can calculate distance matrix follow
eigen::arrayxf sx, sy, sz; eigen::arrayxf rx, ry, rz; eigen::arrayxxf dist; (int s=0; s<nrsources; s++ ) { (int r=0; r<nrreceivers; r++) { dist(h,g) = sqrt(pow(rx(h)-sx(g),2.)+ pow(ry(h)-sy(g),2.)+ pow(sz(h)-sz(g),2.)); } }
i need compute dist array 500 x 1000 times experiment. using for-loop obvious works not efficient method since not make use of vectorization.
rewriting sx, sx, sz , hx, hy , hz sxyz , hxyz arrays should possible.
is possible write equation more efficiently!?
you want discard inner loop in favor of expression. doing so, allow calculations lumped , enable vectorization. assuming r
, s
variables declared eigen::arrayx3f sxyz(nrsources,3), rxyz(nrreceivers,3);
, write outer loop as:
for (int s = 0; s < nrsources; s++) { dist.col(s) = (rxyz.rowwise() - sxyz.row(s)).matrix().rowwise().norm(); }
here use rxyz.rowwise() - sxyz.row(s)
subtract s'th s
r
s. matrix()
needed give access norm()
.
benchmark , compare implementation.
Comments
Post a Comment