-3

Hi found this code on this list and need help converting it to Matlab.

int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
  int i, j, c = 0;
  for (i = 0, j = nvert-1; i < nvert; j = i++) {
    if ( ((verty[i]>testy) != (verty[j]>testy)) &&
     (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
       c = !c;
  }
  return c;
}

nvert: Number of vertices in the polygon. Whether to repeat the first vertex at the end.

vertx, verty: Arrays containing the x- and y-coordinates of the polygon's vertices.

testx, testy: X- and y-coordinate of the test point. (This is from another Stack Overflow question: Point in Polygon aka hit test.

JavaScript version:

function insidePoly(poly, pointx, pointy) {
    var i, j;
    var inside = false;
    for (i = 0, j = poly.length - 1; i < poly.length; j = i++) {
        if(((poly[i].y > pointy) != (poly[j].y > pointy)) && (pointx < (poly[j].x-poly[i].x) * (pointy-poly[i].y) / (poly[j].y-poly[i].y) + poly[i].x) ) inside = !inside;
    }
    return inside;
}

How will this translate in Matlab:

function insidePoly = inpoly(poly, pointx, pointy)
% Code
% return inside
Community
  • 1
  • 1
Simon Hanks
  • 55
  • 2
  • 8
  • Hi my question is pretty simple and I provided a link to the original discussion. The first code is written in C, then someone created a JavaScript version of it. I want to implement it in Matlab and only asking for help to make the code matlab compatible. – Simon Hanks Apr 05 '15 at 15:36
  • Your question is not simple because you don't explain your problem implementing these functions. Do you understand what the code does? Where is your problem reimplementing this in M? – Daniel Apr 05 '15 at 16:16
  • @Daniel so this is the [ray casting algorithm](http://rosettacode.org/wiki/Ray-casting_algorithm) for finding whether a point (x,y) is inside a polygon or not. I am looking to rewrite this same function in matlab. Thanks! – Simon Hanks Apr 05 '15 at 16:56
  • You wrote that you want to implement it, thought this was some kind of assignment and you want to learn programming. Now you ask for an already existing implementation of a specific algorithm which was not mentioned in your question. – Daniel Apr 05 '15 at 21:02

1 Answers1

2

Matlab comes with a build-in function inpolygon which seems to do exactly what you are asking for. No need to reimplement it.

Daniel
  • 36,610
  • 3
  • 36
  • 69