Conditional replacement of a vector of zeros and ones

조회 수: 4 (최근 30일)
David Schwartzman
David Schwartzman 2019년 4월 4일
편집: Andreas Bernatzky 2019년 4월 4일
Hi All,
I have an array of zeros from 1:400 and want to randomly assign ones in 10 positions for every 40 zeros in the sequence.
cycles = 40;
count = 0;
state = zeros(1, 400);
for i = 1:cycles
tempstate = state(count:count+cycles)
for j = 1:10
tempstate(randi(numel(tempstate))) =1
end
count = count + 40
The issue I have is that I want wherever I assign a one to have a zero either side.
But still maintain 10 1's per 40 positions in the sequence.
Appreciate the help.
Thanks,
David

채택된 답변

Andreas Bernatzky
Andreas Bernatzky 2019년 4월 4일
편집: Andreas Bernatzky 2019년 4월 4일
Hey David,
this should do the Job. Sorry for my Variablenaming but I could not consider better names :)
sequence=40;
vectors2create=400/sequence;
amountofOnes=10;
finalVector=[];%end vector
for(a=1:1:vectors2create)
tempVec=zeros(1,40);
for(b=1:1:amountofOnes)
onePos(b)=randi(sequence,1);%determine the positions which become 1
end
tempVec(onePos)=1;%set the positions to 1
finalVector=[finalVector,tempVec];%append the final vector
end
  댓글 수: 4
David Schwartzman
David Schwartzman 2019년 4월 4일
Hi Andreas
Exactly right, someitmes I am seeing 0 1 1 0 in finalVector which is not allowed always needs to be 0 1 0
Thanks
David
Andreas Bernatzky
Andreas Bernatzky 2019년 4월 4일
편집: Andreas Bernatzky 2019년 4월 4일
Should do the work now.
sequence=40;
vectors2create=400/sequence;
amountofOnes=10;
finalVector=[];%end vector
for(a=1:1:vectors2create)
tempVec=zeros(1,40);
onePos=[];
while(length(onePos)<amountofOnes)
tempPos=randi(sequence,1);%determine the positions which become 1
cAP=tempPos-1;%checkAscendingPos
cDP=tempPos+1;%checkDescendingPos
cOP=tempPos;%checkOwnPos
%if non of this position(or neighbouring) does appear in onePos this Position can be accepted
if(isempty(find(cAP==onePos))==1&&isempty(find(cDP==onePos))==1&&isempty(find(cOP==onePos))==1)
onePos(end+1)=tempPos;
end
end
tempVec(onePos)=1;%set the positions to 1
finalVector=[finalVector,tempVec];%append the final vector
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2013b

Community Treasure Hunt

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

Start Hunting!

Translated by