Find the curve connecting points following the gradient

Hello, I'm in the following situation:
dx = 0.1;
dy = 0.1;
x = -2:dx:2;
y = -2:dy:2;
[X,Y] = meshgrid(x,y);
t = peaks(X,Y);
[sx,sy] = gradient(t);
contour(X,Y,t)
hold on
quiver(X,Y,sx,sy)
colorbar
[rm,cm]=find(t==min(t,[],"all"));
[rM,cM]=find(t==max(t,[],"all"));
plot(x(cm),y(rm),'b^',"MarkerFaceColor","b")
plot(x(cM),y(rM),'r^',"MarkerFaceColor","r")
hold off
I would like to connect the blue and red points with a curve which follows the arrows. If there are many I would like to pick the shortest one.
As a bonus point, after that I would also like to create a matrix whose elements represent the curve length for each grid point

 Accepted Answer

Use the command streamline()

1 Comment

I'm pretty sure streamline() does not find the shortest path or shortest path according to some cost function so I'm not sure why you accepted this answer, but whatever, as long as you got what you want.

Sign in to comment.

More Answers (1)

The shortest point is simply the Euclidean distance. If you want to apply some cost function like the path is weighted by the values along it then you can use a process like dynamic programming or the A* algorithm. But there might be some kind of built-in function in an optimization toolbox that I don't know about. Or maybe you can use one of the built-in algorithms to the shortestpath() function.

1 Comment

Besides the shortest distance, I would like to find some path connecting the two points, which also follows the direction of the arrows in the picture above.

Sign in to comment.

Categories

Products

Release

R2021a

Community Treasure Hunt

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

Start Hunting!