how to randomly delete number
1 次查看(过去 30 天)
显示 更早的评论
Hi, i create a 1x3 matrix by using :
M=[0 0 0];
m=round((3-1)*rand(1)+1);
M(m)=1;
and i want to know how i can randomly delete one of the 2 zeros. I thought about starting with
for pos=find(M==0)
end
but i dont know what to do next. Im a beginner. Thanks
0 个评论
采纳的回答
Rik
2018-10-20
编辑:Rik
2018-10-20
Your code looks like you want to randomly fill one location with a one, but it has a bias toward the middle. The code below does not.
M=zeros(1,3);
m=randi(numel(M));%pick a random integer between 1 and the number of elements in M
M(m)=1;
%generate the list of positions with a zero
ind_zero=1:numel(M);ind_zero(m)=[];
%randomly pick 1 element from that list
remove_ind=ind_zero(randperm(numel(ind_zero),1));
%remove the element
M(remove_ind)=[];
1 个评论
Rik
2018-10-23
Did this suggestion solve your problem? If so, please consider marking it as accepted answer. It will make it easier for other people with the same question to find an answer. If this didn't solve your question, please comment with what problems you are still having.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!