有一种明智的方法可以用新值替换矩阵/向量中每个值的 x %,并且随机选择要更改的元素吗?也就是说,在 A 中,如果我想将20%的值(每个现有值1个元素)更改为值5,我该如何确保每个现有值中的5个元素中的每一个 A 有相同的概率更改为新值(例如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];
答案 0 :(得分:0)
尝试使用逻辑数组和生成的随机数,如下所示:
vals_to_change=rand(size(A,1),size(A,2))<p;
A(vals_to_change)=rand(sum(vals_to_change),1);
答案 1 :(得分:0)
使用here和here中的信息,我实现了自己的目标。下面的代码将用矩阵替换矩阵中每个值的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);