在Matlab中使用rand()的随机数 [英] Random numbers using rand() in matlab

查看:386
本文介绍了在Matlab中使用rand()的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Matlab函数round(rand(256))创建大小为256x256的方阵,其随机分布为0和1s.

I am using Matlab function round(rand(256)) to create a square matrix of size 256x256 with random distribution of 0s and 1s.

我特别想做的是,我想以某种方式指定rand()(或与此相关的任何其他相关函数)随机产生并分布在整个矩阵中的1s数.

What I specifically want to do is that I want to somehow specify number of 1s that rand() (or any other relevant function for that matter) to generate and distribute throughout the matrix randomly

推荐答案

Magdrop的答案是最简单的方法,它会计算随机值的百分比来确定阈值.

Magdrop’s answer is the most straight-forward method, it computes the percentile of the random values to determine the threshold.

另外两个选项涉及 randperm :

Another two options involve randperm:

  1. 将所有索引随机排列到矩阵中,然后阈值:

  1. Randomly permute all indices into the matrix, then threshold:

sz = [256,256]; % matrix size
n = 256; % number of zeros
M = randperm(prod(sz)) <= n;
M = reshape(M,sz);

  • 随机排列索引,然后选择n作为索引的位置:

  • Randomly permute indices and select n as the locations of the ones:

    indx = randperm(prod(sz),n);
    M = zeros(sz);
    M(indx) = 1;
    

  • 这篇关于在Matlab中使用rand()的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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