Frey
Frey

Reputation: 325

Matlab code to get connection paths with weights

After I run Matlab program, I get matrices which have only one entry in each row and column.

Mat(:,:,1) = [0 0.3; 0.9 0] - stage 1

Mat(:,:,2) = [0.7 0; 0 0.4] - stage 2

Mat(:,:,3) = [0 0.1; 0.5 0] - stage 3

If I have entry at (i,j)-th position means that this (current) stage i-th node connects with next (future) stage j-th node, and value of entry means its path weight.

As above example:

Mat(:,:,1) says 1st node of stage 1 connects with the 2nd node of stage 2 and 2nd node of stage 1 connects with the 1st node of stage 2.

Mat(:,:,2) says 1st node of stage 2 connects with the 1st node of stage 3 and 2nd node of stage 2 connects with the 2nd node of stage 3.

Mat(:,:,3) says 1st node of stage 3 connects with the 2nd node of stage 4 and 2nd node of stage 3 connects with the 1st node of stage 4.

Then, stage-1 to stage-4 connection paths can be given as with weight:

path1=[0.3, 0.4, 0.5]

path2=[0.9, 0.7, 0.1]

But I do not know how I can get these two path1 and path2 vectors by using Matlab code. This is the simplest example I run for 2 x 2 matrix, but my actual case is general n x n matrix having #n paths.

Can someone please help me to get these paths using matlab when all Mat(:,:,n) matrices are given?

Upvotes: 0

Views: 108

Answers (1)

Saeid
Saeid

Reputation: 4265

First create the adjacency matrix of your implicit graph. Then perform a DFS to find all the paths starting from the first stage:

script.m

Mat = zeros(2,2,3);
Mat(:,:,1) = [0 0.3;0.9 0];
Mat(:,:,2) = [0.7 0;0 0.4];
Mat(:,:,3) = [0 0.1;0.5 0];

Z = size(Mat,3);
N = size(Mat,1);
adjacency = zeros( (Z+1) * N );

for z=1:size(Mat,3)
    for r=1:size(Mat,1)
        for c=1:size(Mat,2)
            if Mat(r,c,z) > 0
                adjacency( (z-1)*N + r , (z)*N + c) = Mat(r,c,z);
            end
        end
    end
end

for i=1:N
    dfs( adjacency, i, [])
end

dfs.m

function dfs(adj, node, path_)
    flag = 0;
    for i=1:size(adj,2)
        if adj(node, i) > 0
            flag = 1;
            dfs(adj,i,[path_ adj(node,i)])
        end
    end
    if flag==0
        path_
    end
end

Output

path_ =

    0.3000    0.4000    0.5000


path_ =

    0.9000    0.7000    0.1000

Upvotes: 1

Related Questions