How to creat topology with FOR loop

Hello everyone,
I'm trying to create random topology, i.e. to connect only specific nodes.
To elaborate better:
Let's say I have matrix
in 1st column (n) are Nodes --> 1,2,3,4,5
in 2nd column (x) are x values of nodes
in 3rd column (y) are y values of nodes
in 5th (a) and 6th (b) column are nodes to which node from 1st column connects to
let's say this is matrix described above (n x y a b):
1 0 0 2 3
2 3 1 4 5
3 1 3 NaN NaN
4 3 7 NaN NaN
5 7 3 NaN NaN
So first I plot nodes
plot(x,y,'o')
hold on
now I want to connect nodes in foward way given in matrix, i.e. node 1 connects to nodes 2 and 3, node 2 connects to nodes 4 and 5, and nodes 3,4,5 don't connect to any node.
I tried some for loop variations none of them worked, seems I simply don't know how to set up for loop to solve this problem.
Any direction and help is appreciated.
Thanks for your time,
Denis.

 Accepted Answer

As Walter suggested, for R2015b or later, use graph objects. Prior to that, take a look at gplot:
data = [...
1 0 0 2 3
2 3 1 4 5
3 1 3 NaN NaN
4 3 7 NaN NaN
5 7 3 NaN NaN];
nnode = size(data,1);
x = data(:,2);
y = data(:,3);
src = repmat(data(:,1), 1, size(data,2)-3);
tar = data(:,4:end);
src = src(~isnan(tar));
tar = tar(~isnan(tar));
% Pre-2015b
adj = sparse(src, tar, ones(size(src)), nnode, nnode);
gplot(adj, [x y]);
hold on;
plot(x, y, 'o');
% 2015b+
G = graph(src, tar);
plot(G, 'XData', x, 'YData', y);

1 Comment

Thank you :) This does the trick for me :) And I can optimize it for any number of nodes, this is great :)

Sign in to comment.

More Answers (1)

If you have a new enough MATLAB, use graph()

1 Comment

Tnx, I know about that option, but I have 2015a...

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!