Replace percentage of existing values with new value
3 次查看(过去 30 天)
显示 更早的评论
Hello, I'd like to replace a percentage of each existing value in a matrix or vector with another value? For example, I have matrix B which has values 1, 2, 3, and 4 and I want to replace 25% of each of these extant values with '5,' is there a sweet way to do this? The result would be matrix C, that is, 25% would mean one element of each extant value changed to / replaced with '5'. I'm afraid I am not sure where to start.
B = [1 1 1 1;
2 2 2 2;
3 3 3 3;
4 4 4 4];
C = [1 1 1 5;
2 2 5 2;
3 5 3 3;
4 4 5 4];
Thank you,
Mike
0 个评论
采纳的回答
Richard Zapor
2012-11-20
function replace25
m = randi(4, 9, 9)
newvalue = 5;
% determine qty of values 1 thru 4, a(1) qty 1, a(4) number 4s
a=hist(m(:),4)
for i=1:4
% find first 25 % of a value and give it new value
m(find(m==i,round(a(i)/4)))=newvalue;
end
m
end
更多回答(2 个)
Matt Fig
2012-11-19
B(randperm(16,4)) = 5
5 个评论
Matt Fig
2012-11-20
编辑:Matt Fig
2012-11-20
O.k. Here is a more generalized code:
N = 4; % This controls the code: a positive integer.
vals = 0:N;
nVals = N + 1;
M = nVals*randi(4); % Up to size nVals*4
idx = floor(linspace(1,nVals+1-2*eps(nVals),M^2));
out_vec = vals(idx);
% orderly unique values, aggregated by row:
out_mat = vec2mat(out_vec,M)
% Now, we have nVals unique values in out_mat.
% So we want 1/4 of the set of each of
% those (M*N) values set to another value,
% say -1 for example....
CV = -1; % The change value, set as needed...
PE = floor(M^2/nVals/4); % 1/4 of the number of each
for ii = 0:M/nVals:M-1
cnt = 0;
while cnt<PE
R = randi(M/nVals) + ii;
C = randi(M);
if out_mat(R,C)~=CV
out_mat(R,C) = CV;
cnt = cnt + 1;
end
end
end
out_mat
Image Analyst
2012-11-20
Michael, I think this code does what you want in a pretty flexible and robust way:
m = int32(randi(4, 9, 9))
replacementValue = 5;
% Get the unique values in m
uniqueValues = unique(m)
% Make a new output array so that the replacement value
% can be one of the input values. This allows
% maximum flexibility and robustness.
% For example what if the replacment value = 3
% without having a copy you'd replace values already replaced.
mOut = m;
for k = 1 : length(uniqueValues)
thisValue = uniqueValues(k)
% Count the number originally at this value.
count = sum(m(:) == thisValue)
% Get the number to replace, rouding up.
numberToReplace = int32(ceil(0.25 * count))
% Pick them from random locations
linearIndexes = randperm(numel(m));
indexesToReplace = linearIndexes(1:numberToReplace);
% Do the assignments.
mOut(indexesToReplace) = replacementValue;
end
% Do the replacements
m = mOut;
% Display final m.
m
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!