MATLAB: Can anyone help me to generate a matrix of 0’s and 1’s randomly in which each contains only one 1 like [ 0 1 0 0 0; 1 0 0 0 0; 0 0 0 1 0].

matrix array

for example
[0 1 0 0 0; 1 0 0 0 0; 0 0 0 1 0]

Best Answer

[~,ii] = sort(rand(3,5),2)
out = ii == 1
or
out = zeros(3,5)
[m,n] = size(out);
out(sub2ind([m,n],1:m,randperm(n,m))) = 1