Random Path Generation between source node and destination node

3 次查看(过去 30 天)
Hello everyone,
I have got Implementation Idea . Can anyone help me to write code.
Suppose i have 5 node network. So, i have 5*5 matrix. My Source node=1 and Destination node=2 and i want to send f=9 units of data.
Rows show my source nodes and columns show my destination nodes,
What i am thinking-Implementation Idea-- 1. Create 5*5 zero matrix. Go to S =1 row.
2. I will have 4 positions available 2,3,4,5 to assign f=9.
3. Suppose 9 is assigned to 5.
4. Then i will go to row 5. next i have positions available 2,3,4.
5. I will go like this until until f=9 goes to position 2.
My outcome should be like=
0 0 0 0 9
0 0 0 0 0
0 0 0 0 0
0 9 0 0 0
0 0 0 9 0
So, my path is 1 to 5 to 4 to 2.
Another example---
0 0 0 0 9
0 0 0 0 0
0 9 0 0 0
0 0 0 0 0
0 0 9 0 0
My path is 1 to 5 to 3 to 2.

回答(1 个)

Geoff Hayes
Geoff Hayes 2014-10-2
Reshdev - you can try something like the following to create a random path between a source and a destination node.
function [randPath,randPerm] = createRandomPath(source,destination,weight,n)
% initialize the path matrix
randPath = zeros(n,n);
% initialize the available nodes array
availNodes = (1:1:n)';
if 0<source && source<=n && 0<destination && destination<=n
% remove the source node from the available nodes array
availNodes(source) = [];
% create a random permutation given the remaining nodes
randPermIdcs = randperm(n-1)';
% the indices define the path to take from node to node
randPerm = availNodes(randPermIdcs);
% clip the random permuation given the destination
destIdx = find(randPerm==destination);
randPerm(destIdx+1:end) = [];
% update the random path matrix
linIdcs = sub2ind(size(randPath),[source;randPerm(1:end-1)],randPerm);
randPath(linIdcs) = weight;
end
The only randomness is in choosing the indices of the available nodes array which we then map back to the available nodes. Any node after the destination node is removed from that random permeation, after which we update the random path. For example,
>> [randPath,randPerm] = createRandomPath(1,2,9,5)
randPath =
0 0 0 0 9
0 0 0 0 0
0 0 0 0 0
0 9 0 0 0
0 0 0 9 0
randPerm =
5
4
2
The randPerm output is the random permutation (that was generated) and the randPath is the path matrix given the source, destination, and random (path) permutation. In the above, we start at the source 1, move to 5, move to 4, and end at 2.

类别

Help CenterFile Exchange 中查找有关 Genetic Algorithm 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by