MATLAB Answers

To generate alternate 0's and 1's

22 views (last 30 days)
brijesh soni
brijesh soni on 14 Aug 2019
Edited: Jos (10584) on 16 Aug 2019
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 Comment

Rik
Rik on 14 Aug 2019
I'm guessing RunLength should help out.

Sign in to comment.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 14 Aug 2019
out = repelem(mod(0:numel(A)-1,2),A);

  1 Comment

brijesh soni
brijesh soni on 15 Aug 2019
Thanks for the answer !

Sign in to comment.

More Answers (2)

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

  0 Comments

Sign in to comment.


Jos (10584)
Jos (10584) on 14 Aug 2019
Edited: Jos (10584) on 16 Aug 2019
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 Comments

Show 1 older comment
Jos (10584)
Jos (10584) on 16 Aug 2019
Sure, but why add an extra + operation?
Andrei Bobrov
Andrei Bobrov on 16 Aug 2019
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) on 16 Aug 2019
Sorry! You're complete right to look only at the last bit!

Sign in to comment.

Sign in to answer this question.