0

是否有一种明智的方法可以用新值替换矩阵/向量中每个值的x %,并随机选择要更改的元素?也就是说,在A中,如果我想将 20% 的值(每个现有值 1 个元素)更改为值 5,我如何确保 A 中每个现有值的 5 个元素中的每一个都具有相同的更改概率到新值(例如 5)?对于完成上述任务的方法,我将不胜感激。

非常感谢你。

% Example Matrix
% M = 5;
% N = 5;
% A = zeros(M, N);
A = [0 0 0 0 0;
     1 1 1 1 1;
     2 2 2 2 2;
     3 3 3 3 3;
     4 4 4 4 4];   

% Example Matrix with 20% of elements per value replaced with the value '5'
A = [0 0 5 0 0;
     1 5 1 1 1;
     2 5 2 2 2;
     3 3 3 3 5;
     4 4 5 4 4];  
4

2 回答 2

0

尝试使用逻辑数组和生成的随机数,如下所示:

vals_to_change=rand(size(A,1),size(A,2))<p;
A(vals_to_change)=rand(sum(vals_to_change),1);
于 2012-11-18T16:34:33.253 回答
0

使用来自这里这里的信息,我能够实现我的目标。下面的代码将用新值替换矩阵中每个值的 x%,然后随机化其在矩阵中该值中的位置。

M = 5;
N = 5;
A = zeros(M, N);
PC = 20; % percent to change
nCells = round(100/PC); % # of cells to replace with new value
A = [0 0 0 0 0;
     1 1 1 1 1;
     2 2 2 2 2;
     3 3 3 3 3;
     4 4 4 4 4]; 
A2 = A+1; % Pad the cell values for calculations (bc of zero)
newvalue = 6;
a=hist(A2(:),5);% determine qty of each value
for i=1:5
    % find 1st instance of each value and convert to newvalue
    A2(find(A2==i,round(a(i)/nCells)))=newvalue;
end;
out = A2-1; % remove padding
[~,idx] = sort(rand(M,N),2); % convert column indices into linear indices
idx = (idx-1)*M + ndgrid(1:M,1:N); %rearrange each newvalue to be random
A = out;
A(:) = A(idx);
于 2012-11-27T21:42:48.803 回答