Question: How to obtain certain matrix?

Hi all,

Let $A$ be a 0-1 square matrix of order $n$. I want to obtain a matrix $D$ from powers $A$, $A^2$, $\dots$, $A^{n-1}$, where the ($i,j$)-element of $D$ is the smallest $k$ for which the ($i,j$)-element of $A^k$ is nonzero. I only consider the non-diagonal elements of $D$.For example, if the matrix $A$ is Matrix( [[0, 1, 0, 0, 0], [1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 0]]), then $D$ shoule be Matrix([[0, 1, 2, 3, 4], [1, 0, 1, 2, 3], [2, 1, 0, 1, 2], [3, 2, 1, 0, 1], [4, 3, 2, 1, 0]]). However, I cannot obtain this result.

The code is as follows.

p := proc ()

   local A, B, D, m, n, k, r;

   A := Matrix([[0, 1, 0, 0, 0], [1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 0]]);

   r := LinearAlgebra:-RowDimension(A);

   D := A;

   for k from 2 by 1 to r-1 do

       B := A^k;

       for m from 1 by 1 to r do

           for n from 1 by 1 to r do

               if m <> n and B[m, n] <> 0 and D[m, n] = 0 then

                    D[m, n] := k

                end if;

           end do;

        end do;

   end do;

   D;

end proc;

By executing this procedure, I obtain D=Matrix([[0,1,2,3,3],[1,0,1,2,3],[2,1,0,1,2],[3,2,1,0,1],[3,3,2,1,0]]), which is not I want.

Thanks.

Please Wait...