如何用特定范围的随机数填充矩阵的列? [英] How to fill columns of a matrix with random numbers of specific range?
本文介绍了如何用特定范围的随机数填充矩阵的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个矩阵100*10
.现在的目标是用特定范围内的随机整数填充矩阵的每一列.现在的问题是每列的随机数范围都会变化.例如,对于第一列,范围是[1,100]
,对于第二列,范围是-10 to 1
,依此类推,直到第10列.
I've a matrix of order 100*10
. Now the objective is to fill each columns of the matrix with random integer within a specific range. Now the problem is for every column the range of the random number changes. For instance, for the first column, the range is [1,100]
, for the second its -10 to 1
and so on till 10th column.
这是我尝试过的:
b = [0,100;-10,1;0,1;-1,1;10,20]
a = []
for i=1 to 10
a[] = [(i:100)' randi(1,100)]
end
如何生成这种形式的矩阵?
How do I generate a matrix of this form?
推荐答案
我目前尚未安装matlab,但我会做类似的事情.
I don't have matlab installed right now, but i would do something like this.
m = 100;
n = size(b, 1);
range = b(:, 2) - b(:, 1);
offset = b(:, 1);
A = round(bsxfun(@minus, bsxfun(@times, rand(m, n), range), offset);
没有循环,它将变为:
M = 100;
N = size(b, 1);
A = zeros(m, n); % preallocate to avoid matrix expansion
for ii = 1:n
A(:, ii) = randi(b(ii,:), m, 1);
end
这篇关于如何用特定范围的随机数填充矩阵的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文