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 .
0 个评论
回答(1 个)
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!