MATLAB: How to find shortest distance in 3D

Hello, Everyone!
I am trying to find the shortest path by using dijkstra's algorithm and I need to input 3-Dimensional nodes into the program.
Each 3-Dimensional nodes have x, y, z coordinates. I am trying to use Nx3 matrix to represent it or maybe Nx4 matrix include the node ID.
I found that there is a function which called graphshortestpath in matlab function.
I want to know that is it possible to input 3-Dimensional nodes and plot a graph to demonstrate the result?
If yes, please tell me how to do it or give me some examples. If the function cannot do it, please tell me how to do it by other methods.
Thank you very much!

Best Answer

You can use shortestpath function to find the shortest path between selected nodes. I believe the solution would be looks like the following.
% Generate 3D nodes coordinages (x,y,z) for 10 nodes
rng('default') % for reproducability
Position = 10*rand(10,3);
% Calculate euclid distance between each nodes
d = pdist(Position);
% Set distance to 0 for 30 node-pairs
pt = randperm(numel(d),30);
d(pt) = 0;
% Convert to Adjacency matrix
d = squareform(d);
% Generate Graph object and store XYZ coordinates in it
G = graph(d);
G.Nodes = array2table(Position,'VariableNames',{'X','Y','Z'});
% Calculate shortest path between node 1 and 10
[P,L] = shortestpath(G,1,10);
% Visualize the result
figure
h = plot(G,'XData',G.Nodes.X,'YData',G.Nodes.Y,'ZData',G.Nodes.Z);
highlight(h,P,'EdgeColor','r','LineWidth',2)
% Display the path length
disp(L)
graph.png
Related Question