Matrix 从矩阵中保留随机值

Matrix 从矩阵中保留随机值,matrix,octave,Matrix,Octave,我有一个矩阵,它包含N个条目,每个条目有M行。每行包含0和1。我想创建一个大小相同的第二个矩阵,但每行只剩下一个1,其他值都应该是0。应随机选择哪个值应为1 例如: 阅读和的文档 观察代码的运行情况 0 1 1 0 1 1 1 0 0 1 0 0 1 1 0 -> 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 %//preallocate the output matrix out = zeros(size(a)); %for each row, take a rando

我有一个矩阵,它包含N个条目,每个条目有M行。每行包含0和1。我想创建一个大小相同的第二个矩阵,但每行只剩下一个1,其他值都应该是0。应随机选择哪个值应为1

例如:

阅读和的文档

观察代码的运行情况

0 1 1 0 1
1 1 0 0 1
0 0 1 1 0
->
0 1 0 0 0
1 0 0 0 0
0 0 0 1 0
%//preallocate the output matrix
out = zeros(size(a));

%for each row, take a random sample from the indices holding value 1     
for i = 1:size(a,1)
     temp2 = find(a(i,:));
     out(i,temp2(randperm(numel(temp2))(1))) = 1;
end