To generate alternate 0's and 1's

조회 수: 10 (최근 30일)
brijesh soni
brijesh soni 2019년 8월 14일
편집: Jos (10584) 2019년 8월 16일
Say I have A=[2 4 3 4 100 253 77 10 45]. I want to generate alternate 0's and 1' such that we have 2 zeros (i.e, zeros equal to size of 1st element), then 4 ones (ones equal to the size of 2nd element) and so on
Result should be : [0 0 1 1 1 1 0 0 0 1 1 1 1 . . . .]. How to do this?
  댓글 수: 1
Rik
Rik 2019년 8월 14일
I'm guessing RunLength should help out.

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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 8월 14일
out = repelem(mod(0:numel(A)-1,2),A);

추가 답변 (2개)

dpb
dpb 2019년 8월 14일
One brute force way--
B=[];
for i=1:numel(A)
B=[B (1-mod(i,2))*ones(1,A(i))];
end

Jos (10584)
Jos (10584) 2019년 8월 14일
편집: Jos (10584) 2019년 8월 16일
bitget(repelem(0:numel(A)-1, A), 1)
[update] I modified my original but erroneous answer bitget(repelem(1:numel(A), A), 2). In his comments below, Andrei hit a serious flaw in this one. One does need to look at the last bit!
Thanks Andrei, for pointing this out.
  댓글 수: 4
Andrei Bobrov
Andrei Bobrov 2019년 8월 16일
편집: Andrei Bobrov 2019년 8월 16일
Hi Jos!
What am I doing wrong?
My laptop:
>> A=[2 4 3 4]
A =
2 4 3 4
>> bitget(repelem(1:numel(A), A), 2) % your variant
ans =
0 0 1 1 1 1 1 1 1 0 0 0 0
>> bitget(repelem(2:numel(A)+1, A), 1) % with change
ans =
0 0 1 1 1 1 0 0 0 1 1 1 1
>> bitget(repelem(0:numel(A)-1, A), 1) % or
ans =
0 0 1 1 1 1 0 0 0 1 1 1 1
>>
Jos (10584)
Jos (10584) 2019년 8월 16일
Sorry! You're complete right to look only at the last bit!

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by