1 view (last 30 days)

Show older comments

Hello everyone,

My name is Casey Reyes and I am an undergraduate student working on research with metallographys at Wichita State University. I have created a program that takes an image in which I then manually create a curve from points that I select on the picture using the gtpts function. Then from there I use a nested for loop through each pixel on the screen which I then find the distance from that pixel to every point on the curve(I set it to 100 points on the curve). I do this so I can find the minimym distance from that pixel on the screen to the curve. Well, this takes forever and I have looked at alternative ways and I have tried using pdist and pdist2 and havent been able to get away from the nested for loop. Can anyone help me with this problem or send me in the right direction?

Let me include my code that i am using to find these distances:

for s = x(1,:) % x-position of pixel

for t = y(:,1)' % y-position of pixel

d = zeros(size(pt,1)-1,lines); %distance matirx

direction_indicator = zeros(size(pt,1)-1,3,lines); %vector from point on curve to pixel

for k = 1:lines % looping through each slip line

for w = 1:size(pt,1)-1% size of the points used to create slip line

[~,direction_indicator(w,:,k)] = point_to_line([t,s,0],[pt(w,2,k),pt(w,1,k),0],[pt(w+1,2,k),pt(w+1,1,k),0]);

d(w,k) = norm(direction_indicator(w,:,k));

end

end

Aditya Patil
on 15 Jul 2021

As per my understanding, you have a set of points (let us say P) and each of them has a corresponding set of line segments (say Li for each Pi). Then, you want to find the nearest segment for each point.

The pseudo code for this should look like this,

for each Pi

for each Li

dist = distance(Pi, Li)

mindist(Pi) = min(mindist(Pi), dist)

end

end

However, I see four for loops in the code snippet you have provided.

Coming to the optimizations, as the calculations for each of the point-segment combinations are independent, we can parallelize this code. There are multiple options available,

- Vectorize the code. Update the function point_to_line to take vector of P, and a matrix of L as input, and then calculate the distance as a matrix operation(s).
- Use parfor. You can combine this with vectorization.
- Use GPU Coder. Keep the for loops and convert them to kernels.

As for the calculation of distance, it is

- Perpendicular distance from point to segment if the perpendicular intersection falls on the segment
- Otherwise, Smaller of the distance from the two vertices.

In your specific case, it might also be worth checking if there is any relationship between the closest segment, and the closest vertex (that is, whether the closest vertex is part of the closest segment. If so, you can simply calculate the Euclidean distance from all vertices.

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!