MATLAB函数替换randi生成矩阵

MATLAB function to replace randi to generate a matrix

我有一个 matlab 问题要解决。有两个向量限制我的 space、x_low 和 x_high。矩阵 pos 需要在此 spaces 内具有值,并且矩阵的每一列都具有由两个向量给出的不同边界。现在我的问题是 randi 给出了两个整数之间的值,但我需要更改每列的界限。还有另一种方法可以使用 randi 或不同的 matlab 函数来做到这一点吗? 我知道有更好的代码可以做到这一点,但我开始使用 matlab 并且我知道这样做,欢迎任何帮助

x_low = [Io_low, Iirr_low, Rp_low, Rs_low, n_low];   % vector of constant values
x_high = [Io_high, Iirr_high, Rp_high, Rs_high, n_high];    % vector of constant values 
pos = rand(particles, var);
var = length(x_high);
for i = 1: particles        % rows                                                   
  for k = 1: var         %columns                                    
    if pos(i, k) < x_low(k) || pos(i, k) > x_high(k)    % if the position is out of bounder     
        pos(i, k) = randi(x_low(k), x_high(k), 1);    % fill it with a particle whithin the bounderies     
    end
  end
end

您可以为此使用 cellfun。类似于:

x_low = [Io_low, Iirr_low, Rp_low, Rs_low, n_low];
x_high = [Io_high, Iirr_high, Rp_high, Rs_high, n_high];

pos = cell2mat(cellfun(@randi, mat2cell([x_low' x_high'], ones(numel(x_low),1), 1), repmat({[particles 1]}, [numel(x_low) 1)])))';

最佳,

如果我没理解错的话,你需要生成一个具有整数值的矩阵,使得每一列都有不同的下限和上限;并且包含下限和上限。

这可以非常简单地完成

  • rand(生成0到1之间的随机数),
  • bsxfun(以列为单位处理下限和上限),以及
  • round(这样结果就是整数值)。

让输入数据定义为

x_low =  [1  6  11];  %// lower limits
x_high = [3 10 100];  %// upper limits
n_rows = 7;           %// number of columns

然后:

r = rand(n_rows, numel(x_low));                %// random numbers between 0 and 1
r = floor(bsxfun(@times, r, x_high-x_low+1));  %// adjust span and round to integers
r = bsxfun(@plus, r, x_low);                   %// adjust lower limit

给出类似

的东西
r =
     2     7    83
     3     6    93
     2     6    22
     3    10    85
     3     7    96
     1    10    90
     2     8    57

如果您只需要在矩阵 pos 的特定条目处填写值,您可以使用

ind = bsxfun(@lt, pos, x_low) | bsxfun(@gt, pos, x_high); %// index of values to replace
pos(ind) = r(ind);

这有点矫枉过正,因为生成整个矩阵 r 只是为了使用其中的一些条目。要仅生成所需的值,最好的方法可能是使用循环。