Change the value of a percentage of elements , randomly, ina vector

1 次查看(过去 30 天)
Hi there, I am looking for an efficient way to change the value (set) of a predetermined percentage of elements in a vector, where the elements are selected randomly. For example, let say I have a vector of 100 elements and I wold like to set the value of 10% (or any other percentage) of them to '1'. The index of the selected elements are to be chosen RANDOMLY .

回答(1 个)

Akira Agata
Akira Agata 2018-3-9
Like this?
% Sample vector of 100 elements
x = rand(100,1);
% Percentage
p = 0.2;
% One solution:
nSelect = round(numel(x)*p);
idx = randperm(numel(x),nSelect);
x(idx) = 1;
% Another solution (needs 'Statistics and ML Toolbox'):
cv = cvpartition(numel(x),'HoldOut',p);
x(cv.test) = 1;

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by