您必须设置某种映射,将从您从 rand 获得的均匀分布的随机数映射到您想要的值,即相对于想要的分布。
在我的解决方案中,我使用rand 生成随机数,并将它们映射到整数1、2、3、4 以及(分类)字符A、@987654329 @、C、D。我构建了一个完整的函数来支持可变数量的输入参数来模仿rand 的行为。
这是myRand函数的代码:
function [rn, in, ch] = myRand(varargin)
% No input arguments.
if (numel(varargin) == 0)
rn = rand();
% One input argument; might be a scalar or an array.
elseif (numel(varargin) == 1)
a = varargin{1};
if (!isnumeric(a))
error('myRand: argument must be numeric');
end
rn = rand(a);
% More than one input argument; must be scalars.
elseif (numel(varargin) > 1)
if (!all(cellfun(@(x)isnumeric(x), varargin)))
error('myRand: arguments must be numeric');
end
if (!all(cellfun(@(x)isscalar(x), varargin)))
error('myRand: arguments must be scalar');
end
rn = rand(varargin{:});
end
in = zeros(size(rn));
in((0 <= rn) & (rn < 0.1)) = 1;
in((0.1 <= rn) & (rn < 0.5)) = 2;
in((0.5 <= rn) & (rn < 0.9)) = 3;
in((0.9 <= rn) & (rn < 1)) = 4;
ch = cell(size(rn));
ch((0 <= rn) & (rn < 0.1)) = { 'A' };
ch((0.1 <= rn) & (rn < 0.5)) = { 'B' };
ch((0.5 <= rn) & (rn < 0.9)) = { 'C' };
ch((0.9 <= rn) & (rn < 1)) = { 'D' };
end
还有,下面是一些带有相应输出的测试代码:
% Single random number with integer and category
[rn, in, ch] = myRand()
% Multiple random numbers with integers and categories (array input)
[rn, in, ch] = myRand([2, 3])
% Multiple random numbers with integers and categories (multiple scalars input)
[rn, in, ch] = myRand(2, 3)
rn = 0.19904
in = 2
ch =
{
[1,1] = B
}
rn =
0.206294 0.420426 0.835194
0.793874 0.593371 0.034055
in =
2 2 3
3 3 1
ch =
{
[1,1] = B
[2,1] = C
[1,2] = B
[2,2] = C
[1,3] = C
[2,3] = A
}
rn =
0.96223 0.87840 0.49925
0.54890 0.88436 0.92096
in =
4 3 2
3 3 4
ch =
{
[1,1] = D
[2,1] = C
[1,2] = C
[2,2] = C
[1,3] = B
[2,3] = D
}
希望有帮助!
免责声明:我使用 Octave 5.1.0 测试了代码,但我很确定它应该与 MATLAB 完全兼容。如果没有,请发表评论,我会尽力解决可能的问题。