[英]How to generate a random binary matrix where only one bit in each row has value 1?
I want to use MATLAB to generate a random binary matrix A
(nxm) which satisfies a condition: 我想用MATLAB生成满足条件的随机二进制矩阵A
(nxm):
Each row contains one position with value 1
. 每行包含一个值为1
位置。 Other positions are value 0
. 其他职位为0
。 The position having 1
value is random position. 具有1
值的位置是随机位置。
I tried this code 我试过这段代码
n=5;m=10;
%% A = randi([0 1], n,m);
A=zeros(n,m);
for i=1:n
rand_pos=randperm(m);
pos_one=rand_pos(1); % random possition of 1 value
A(i,pos_one)=1;
end
Is it correct? 这是正确的吗?
The solution works, but it is inefficient. 解决方案有效,但效率低下。
You are using randperm
to create a vector (array), and then use only the first element of the vector. 您正在使用randperm
创建向量(数组),然后仅使用向量的第一个元素。
You can use randi
to create a scalar (single element) instead: 您可以使用randi
来创建标量(单个元素):
n=5;m=10;
A=zeros(n,m);
for i=1:m
%rand_pos gets a random number in range [1, n].
rand_pos = randi([1, n]);
A(rand_pos, i)=1;
end
You can also use the following "vectorized" solution: 您还可以使用以下“矢量化”解决方案:
rand_pos_vec = randi([1, n], 1, m);
A(sub2ind([n, m], rand_pos_vec, 1:m)) = 1;
The above solution: 以上解决方案:
sub2ind
to convert "row index" to "matrix index". 使用sub2ind
将“行索引”转换为“矩阵索引”。 You can do it in one line using bsxfun
and randi
: 你可以使用bsxfun
和randi
在一行中randi
:
A = double(bsxfun(@eq, 1:m, randi(n, n, 1)));
This compares the row vector [1 2 ... m]
with an n
× 1
random vector of values from 1
to n
. 这将行向量[1 2 ... m]
与值为1
到n
的n
× 1
随机向量进行比较。 The comparison is done element-wise with singleton expansion. 通过单独扩展进行元素比较。 For each row, exactly one of the values of [1 2 ... m]
equals that in the random vector. 对于每一行, [1 2 ... m]
的值中的一个恰好等于随机向量中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.