MATLAB: Matrix with at most one 1 per row

binarymatrix arrayone

Hi,
I want to create a binary 2D matrix with at most one '1' per row. This '1' should be at a random column in each row. Can anyone provide me help on this?
thank you in advance

Best Answer

A=zeros(4)
n=size(A,1)
idy=randperm(n)
idx=1:n
idxy=sub2ind(size(A),idx,idy)
A(idxy)=1
If the matrix is not square
A=zeros(7,5)
[n,m]=size(A);
idy=randi(m,1,n)
idx=1:n
idxy=sub2ind(size(A),idx,idy)
A(idxy)=1