I have the matrices
$$A = \begin{bmatrix}0 & 1 & 0 & 0 & 1\\ 0 &0& 1& 1& 0\\ 1& 0& 0& 0& 0\\ 1& 0& 0& 0& 1\\ 0& 1& 0& 1& 0\end{bmatrix}$$
$$M=A+A^2 = \begin{bmatrix}0& 2& 1& 2& 1\\ 2& 0& 1& 1& 1\\ 1& 1& 0& 0& 1\\ 1& 2& 0& 1& 2\\ 1& 1& 1& 2& 1\end{bmatrix}$$
I want to to know the minimum number of zeroes in $A$ I can replace by ones in order for $M$ to have all elements non-zero.
I created a nested for-loop, within a while loop in order to break the entire thing once the desired $M$ is constructed. Here is my code:
go = true;
while (go == true)
for i = 1:5
for j = 1:5
if( A(i,j) == 0)
A(i,j) = 1;
M = A+A^2;
if ((numel(M)-nnz(M)) == 0)
disp(M)
go = false;
end
end
end
end
end
The result I get is 13 different computations of $M$ and the foor loop ends once all elements in $M$ are $6.$
What is wrong?
I've also tried this variant of while loop:
while (1)
for i = 1:5
for j = 1:5
if( A(i,j) == 0)
A(i,j) = 1;
M = A+A^2;
if ((numel(M)-nnz(M)) == 0)
disp(M)
go = false;
end
end
end
end
end
but with the same result.
By looking at the zeroes in $A+A^2$, you see that the following two changes take care of everything: $$A = \begin{bmatrix}0 & 1 & \color{red}X & 0 & 1\\ 0 &0& 1& 1& 0\\ 1& \color{red}X& 0& 0& 0\\ 1& 0& 0& 0& 1\\ 0& 1& 0& 1& 0\end{bmatrix}$$ It's impossible to do better since one change will affect only the entries in the corresponding row and column.
As for the code,
go=false;doesn't mean the program will stop at that point. It will stop the next time it tries to get into thewhileloop again, which means when allforloops are done anyway.A way around is to use the BREAK command repeatedly, using a dummy variable such as your
go, as discussed here. Here is how to implement it here (I don't have matlab right now so I can't test it but that's the idea):Note however that this won't give you the minimum, but only some solution.