Search code examples
matlabsplitadjacency-matrixedges

Spread elements of rows to multiple rows


I am working on graph theory using adjacency matrix, I want to split the edges between multiple nodes for instance I have the following initial adjacency matrix :

    a= [ 0 2 3;
         2 0 1;
         3 1 0]

From that matrix its clear that we have 3 nodes, Now I want to split the aforementioned rows (edges) into new random nodes between (1-3) :

 split= randi([1 3],1,length(A));
 split = [ 2 2 1]

I know now that I need to split the elements of the first row into two rows, the elements of the second rows also into two rows, while the elements of th third row will remain as is, and I'll have new matrix with size 5X5 as following:

    A = [0 0 2 0 3;
         0 0 0 0 0;
         2 0 0 0 1;
         0 0 0 0 0;
         3 0 1 0 0]     

What I want to do is to split the non-zero elements in the first row between this row and the second row, and the third with the fourth, so my matrix will look like:

    An = [0 0 2 0 0;
          0 0 0 0 3;
          2 0 0 0 0;
          0 0 0 0 1;
          0 3 0 1 0]

Solution

  • It's not fully clear to me what's the initial point, the prerequisites and conditions. I assume that every second row/column is a row/column of zeros. I furthermore assume that the non-zero rows/columns have exactly two non-zero values whereas the second value should be moved to the next row/column. For this, I'd suggest:

    A = [0 0 2 0 3 ; 0 0 0 0 0 ; 2 0 0 0 1 ; 0 0 0 0 0 ; 3 0 1 0 0];
    
    for n = 1:2
        if n==2
            A = A';
        end % if
        for k = 1:2:size(A,1)-1
            m = find(A(k,:));
            A(k+(0:1),m(end)) = flipud(A(k+(0:1),m(end)));
        end % for
        if n==2
            A = A';
        end % if
    end % for
    
    A
    
    A =
    
         0     0     2     0     0
         0     0     0     0     3
         2     0     0     0     0
         0     0     0     0     1
         0     3     0     1     0