matlab - How to vectorize a pair-wise point inside rectangle (bounding box) check? -


p m*2 matrix of m points([x y]), , r n*4 matrix of n rectangles ([x1 y1 x2 y2]). want form m*n matrix, c, in way c(i, j) indicates if i-th point in p lies inside j-th rectangle in r.

single point single rect:

this way check if point lies inside rectangle:

c = (p(1)>=r(1))&(p(1)<=r(3))&(p(2)>=r(2))&(p(2)<=r(4)); 

for more readability:

c = (px>=rxmin)&(px<=rxmax))&(py>=rymin)&(py<=rymax); 

in code above i’m sure r(1)<=r(3) , r(2)<=r(4):

r(:, [1 3]) = sort(r(:, [1 3]), 2); r(:, [2 4]) = sort(r(:, [2 4]), 2); 

multiple points multiple rects:

it's easy mange m*1 , 1*n cases (like second answer here). don't know how vectorize m*n case. i’m doing using loops:

m = size(p, 1); n = size(r, 1); c = false(m, n); i=1:n     c(:, i) = (p(:, 1)>=r(i, 1))&(p(:, 1)<=r(i, 3))& ...         (p(:, 2)>=r(i, 2))&(p(:, 2)<=r(i, 4)); end 

how can vectorize more efficiency?

i suggest work each column of p , r individually , bitwise & them @ end:

px = p(:,1); rx1 = r(:,1).'; rx2 = r(:,3).';  x1 = bsxfun(@ge, px, rx1); x2 = bsxfun(@le, px, rx2);   py = p(:,2); ry1 = r(:,2).'; ry2 = r(:,4).';  y1 = bsxfun(@ge, py, ry1); y2 = bsxfun(@le, py, ry2);  c = x1 & x2 & y1 & y2 

or if prefer:

c = bsxfun(@ge, p(:,1), r(:,1).')& ...  % x lower bound     bsxfun(@le, p(:,1), r(:,3).')& ...  % x upper bound     bsxfun(@ge, p(:,2), r(:,2).')& ...  % y lower bound     bsxfun(@le, p(:,2), r(:,4).');      % y upper bound 

op has provided timing comparison

enter image description here


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -