how to randomly delete number

1 次查看(过去 30 天)
Elie Elias
Elie Elias 2018-10-20
评论: Rik 2018-10-23
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

采纳的回答

Rik
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
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 CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by