# I have a 4x4 array of 1's and I need to turn 3 of 4 ones to zero per row at random. So there will be a one 1 left in each row.

1 view (last 30 days)
Jesse Brimeyer on 8 May 2022
Commented: Jan on 9 May 2022
A = [1 1 1 1; 1 1 1 1; 1 1 1 1; 1 1 1];
B = [1 0 0 0; 0 0 1 0; 0 1 0 0; 0 0 0 1]; % An example
##### 2 CommentsShowHide 1 older comment
Torsten on 8 May 2022
Better start with a zero matrix and replace one of the four zeros by a one in each row.

Jan on 8 May 2022
Edited: Jan on 9 May 2022
Instead of starting with ones and set all but one to zero, it is cheaper to start with zeros and set one element to 1 per row:
n = 4;
A = zeros(n, n);
A(sub2ind([n, n], 1:n, randi([1,n], 1, n))) = 1
A = 4Ã—4
0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 1
##### 2 CommentsShowHide 1 older comment
Jan on 9 May 2022
@the cyclist: Thanks.

the cyclist on 8 May 2022
Here is one way:
N = 4;
x = (1:N)';
y = randi(N,N,1);
linearIndex = sub2ind([N,N],x,y);
B = zeros(N,N);
B(linearIndex) = 1
B = 4Ã—4
0 1 0 0 0 0 0 1 0 0 1 0 0 0 1 0