MATLAB: The global value changes for every iteration

globalvariablematrix manipulation

for iter=1:3
global ko;
ko = 2;
disp(sprintf('Iter %d: ', iter))
for i=1:4
perm=randperm(8);
for j=1:ko
s(perm(j),i)=1;
end
end
s
pause
iter=iter+1;
end
I'm trying to create a matrix of size [8×4] and the value for each is randomly assign 1 and must not exceed the variable ko. However, for every iteration, the number of 1 assign is exceeding the value of ko. Is there any problem to my code?
Sample answer:
Iter 1:
s =
0 1 0 0
0 0 0 0
0 0 0 1
1 0 1 0
1 0 1 0
0 0 0 0
0 0 0 1
0 1 0 0
Iter 2:
s =
1 1 1 1
0 0 1 0
0 0 0 1
1 0 1 0
1 0 1 1
0 1 0 0
0 0 0 1
0 1 0 0
Iter 3:
s =
1 1 1 1
0 0 1 0
0 0 0 1
1 1 1 0
1 0 1 1
1 1 0 1
0 0 1 1
0 1 1 1

Best Answer

No mystery at all. Your ‘perm’ variable (vector) contains the integers from 1 to 8 in some permutation. You are using those integers to form the row subscripts to ‘s’. Your ‘j’ index simply chooses two of them for the same value of the column index ‘i’ (that goes from 1 to 4), and sets whatever row and column index that creates equal to 1, giving you the (8x4) matrices for ‘s’ that you see.
If you look at the indices themselves through the loop, you will see that it can overwrite the same row, setting a different column to 1. You only see the result of the last time a particular row was written.
So there is nothing wrong with ‘ko’, although there are a large number of solid reasons to not use global variables. It is not obvious to me why you are using them here.