Questa linea

Z[i][j]=0

non deve stare fuori dal ciclo ma tra il secondo e il terzo