how to randomly delete number
조회 수: 2 (최근 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!