创建具有10%,..,90%零的随机矩阵

时间:2019-01-27 14:46:16

标签: matrix octave

我正在尝试创建一个矩阵,其矩阵的值在-1和1之间,并且在Matlab中为10%,20%,...,90%零。到目前为止,我是

numRows = 100;                        % Number of Rows
numCols = 2*numRows;                  % Number of Columns
percentageZeros = 0.1 : 0.1 : 0.9;    % Percentage of Zeros (options)


for currPercentageZeros = percentageZeros

  do 
    A = zeros(numRows, numCols);   % Initialize matrix

    for row = 1:numRows
      for col = 1:numCols
        rnd = rand;
        if rnd > currPercentageZeros
          A(row, col) = 2*rand-1;
        endif  
      endfor
    endfor
  until (rank(A) == numRows)

但这并不是很准确。有谁知道更好的解决方案?

1 个答案:

答案 0 :(得分:0)

假设您希望数组的其余部分在-1和1之间均匀分布

numRows = 100;
numCols = 2*numRows;
percentageZeros = 0.1 : 0.1 : 0.9;

for i = 1:length(percentageZeros)
  r = rand(numRows, numCols); % create an array of random floats between 0 and 1
  A = 2 * rand(numRows, numCols) - 1; % create your output array between -1 and 1
  A(r <= percentageZeros(i)) = 0; % use r to decide which elements to remove from A
end