A structure variable measurement contains cloud of 4 points with coordinates (x,y,z).
Distance d between any two points (X,Y,Z) and (x,y,z) is d= Sqrt[(X-x)^2 + (Y-y)^2 + (Z-z)^2].
Now there are a 100 000 entries in a table simulation, each entry is some point in a space, in no specific order. Given any point (X,Y,Z) from the simulation find the nearest point from the cloud of points in variable measurement. An index (1, 2, 3, or 4) is sufficient.
So far, I am using for loop going from over all of the rows and calling function findNearestNeighbor, which requires additional Matlab toolbox. After every loop I receive the index of closest point inside the cloud and append it to an array closestPoint. After the loop is finished, the table measurement receives the fourth column indexOfClosesPoint.
My problem is that the loop is time consuming, because the calling findNearestNeighbor here is the bottleneck. How would you
- find the closest distance from each of 100 000 points to the cloud of 4 points time efficiently. findNearestNeighbor is doing its work, but maybe there is way to do it simplier
- store the indices (1, 2, 3, or 4) into the table simulation and wirte it in an text file.
The structure variable measurement and the table simulation you will find in the attachment.
closestPoint = ;
for iRow = 1:height(measurement)
best = findNearestNeighbor(simulation.x(iRow),...
closestPoint(end+1) = best;
simulationNew = addvars(simulation, closestPoint.',
function in a separate file findNearestNeighbor.m:
function indices = findNearestNeighbor(x, y, z, measurementValues)
a = [vertcat(measurementValues.x), vertcat(measurementValues.y),...
ptCloud = pointCloud(a);
point = [x, y, z];
K = 1;
[indices,~] = findNearestNeighbors(ptCloud,point,K);