Matlab生成具有随机元素的矩阵 [英] Matlab Generating a Matrix with random elements

查看:358
本文介绍了Matlab生成具有随机元素的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何生成具有布尔元素的矩阵,但是每一行的总和等于某个常数.

How can I generate a Matrix with Boolean elements, but the sum of each row is equal to a certain constant number.

推荐答案

让我们说您要有20列(n=20),向量a包含每行所需的列数:

Lets say you want to have 20 columns (n=20) and your vector a contains the number of ones you want in each row:

n=20;
a= [5 6 1 9 4];
X= zeros(numel(a),n);
for k=1:numel(a)
    rand_order=randperm(n);
    row_entries=[ones(1,a(k)),zeros(1,n-a(k))];
    row_entries=row_entries(rand_order);
    X(k,:)=row_entries;
end
X=boolean(X);

我要做的是为我生成一个随机有序索引数组rand_order,然后得到一个包含所需数量的零填充数组.根据rand_order重新排序这些元素,将其保存并转换为逻辑.而且由于一直使用for循环rand_order,因此始终会对其进行计算,因此为您的输出提供了不同的位置:

What I do is generate me a random ordered index array rand_order then getting an array which contains the wanted number of ones filled with zero. Reorder those elements according to rand_order saving it and converting it to logical. And because of the use of a for loop rand_order is all the time computed again, so giving you different locations for your output:

 1     0     0     0     0     0     0     0     0     1     0     0     0     0     0     1     1     1     0     0
 0     0     0     1     0     0     0     1     1     0     1     0     0     0     0     0     1     1     0     0
 0     0     0     0     0     0     0     0     0     0     0     0     1     0     0     0     0     0     0     0
 1     0     0     1     0     1     1     0     1     0     0     1     1     0     0     0     1     1     0     0
 1     0     0     0     1     0     0     0     0     0     1     0     1     0     0     0     0     0     0     0

这篇关于Matlab生成具有随机元素的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆