MATLAB: Start every iteration of for loop with same matrix

for loopmatrix

How can I make sure, that every iteration of my for loop starts with the same initial matrix? At the moment, it gets overwritten every time, such that I end up with an n by n matrix full of inf´s
function[o1,o2]=find_bestconnection(x,s)
%x is a reduced matrix
%s is the starting point, from which the connections need to be found
x(s,:)=inf;
for n=1:length(x)
x(:,n)=inf;
x(n,s)=inf;
[reduced_node_matrix,cost] = reduction(x)
end
end
It should work in such a way, that in each loop, the matrix x is taken and the column n and the element (n,s) are set to inf and then the function "reduction" is applied.
As example:
Inf 1 Inf 2 1 0
2 Inf 0 2 1 Inf
Inf 1 Inf 0 Inf Inf
4 3 0 Inf 6 Inf
1 0 Inf 4 Inf 0
0 Inf Inf Inf 0 Inf
Should become for n=4
Inf Inf Inf Inf Inf Inf
2 Inf 0 Inf 1 Inf
Inf 1 Inf Inf Inf Inf
4 3 0 Inf 6 Inf
1 0 Inf Inf Inf 0
0 Inf Inf Inf 0 Inf
However, my code gives me:
Inf Inf Inf Inf Inf Inf
Inf Inf Inf Inf 1 Inf
Inf Inf Inf Inf Inf Inf
Inf Inf Inf Inf 6 Inf
Inf Inf Inf Inf Inf 0
Inf Inf Inf Inf 0 Inf

Best Answer

Simply make a copy inside the loop, and work on the copy only:
for n = 1:length(x)
y = x;
y(:,n) = Inf;
y(n,s) = Inf;
[reduced_node_matrix,cost] = reduction(y);
end
Note that the output from length changes depending on the size of the inputs. If you want to write reliable code then you should always use size or numel instead of length.