/* function d = find_min_dist(line_x,line_y,x,y) Given a grid (x,y) and a line (line_x,line_y) compute the minimum distance from each point of (x,y) to a point on the line. Written by George Beckett - Matlab 5.3 MEX, Friday 7th April 2000. */ /* All MEX prototypes are stored in the mex.h header file which must be included. */ #include #include "mex.h" #define DEBUG 0 #define LARGEST_DOMAIN 100 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ unsigned int i,j, k; unsigned long int loc = 0; /* counter */ unsigned int m, n, n2; /* dimension stores */ double *plx = NULL, *ply = NULL; /* pointers to matrices */ double *px = NULL, *py = NULL, *pd = NULL; double dist, min_dist; /* temporary stores */ /* Firstly, validate input and output arguments. */ if(nrhs != 4) mexErrMsgTxt("Invalid no. input arguments."); else if(nlhs != 1) mexErrMsgTxt("Invalid no. output arguments."); /* Then read input arguments. */ plx = (double *)mxGetPr(prhs[0]); ply = (double *)mxGetPr(prhs[1]); px = (double *)mxGetPr(prhs[2]); py = (double *)mxGetPr(prhs[3]); /* Get size of grid matrices and length of line vector. */ m = mxGetM(prhs[2]); n = mxGetN(prhs[2]); n2 = mxGetN(prhs[0]); /* Allocate space for the minimum distance matrix. */ plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL); if(plhs[0] == NULL) mexErrMsgTxt("Could not create matrix min_dist. Memory?"); pd = (double *)mxGetPr(plhs[0]); /* Step through the mesh one point at a time. */ for(j = 0; j < n; j++){ for(i = 0; i < m; i++){ min_dist = LARGEST_DOMAIN; /* Step along the line a point at a time. */ for(k = 0; k < n2; k++){ dist = (plx[k]-px[loc])*(plx[k]-px[loc]) + \ (ply[k]-py[loc])*(ply[k]-py[loc]); if(dist < min_dist) min_dist = dist; } pd[loc++] = min_dist; } } /* No housekeeping to be done here. */ return; }