Hi everybody, I want different scenarios of a vector with 0 and 1 elements. For example v=[0 0 0 0 0 0 0], v=[0 1 0 1 0 1 0 ] , v=[0 1 1 1 1 1 1] and so on. But the first element of vector is fixed and has be zero .
1 次查看(过去 30 天)
显示 更早的评论
采纳的回答
Guillaume
2015-11-9
"Thank you very much. But I need all 64 different scenarios."
You should have asked that to start with.
Your example uses 7 bits, that would be 128 different scenarios, if you vary all the bits. Regardless, to get the first 64 binary numbers
dec2bin(0:63, 7) - '0'
0 个评论
更多回答(2 个)
arich82
2015-11-9
Use dec2bin with its second argument:
>> n = 6;
>> a = dec2bin(0:2^n-1, n+1)
a =
0000000
0000001
0000010
0000011
0000100
0000101
0000110
0000111 ...
[remaining output elided]
Note that this returns a char array. If you need an array of doubles, you can "cheat" to convert it by subtracting the string '0':
a = dec2bin(0:2^n-1, n+1) - '0';
Alternatively, you can use bitget, wrapped inside a call to bsxfun:
a = bsxfun(@bitget, [0:2^n-1].', n+1:-1:1);
Please accept this answer if it helps, or let me know in the comments if I missed something.
3 个评论
Guillaume
2015-11-9
You can only accept one answer. Once you've accepted an answer you can't change your mind (as far as I know).
You can still vote for arich82's answer (click on the grey triangle next to the answer) to give him reputation points.
arich82
2015-11-9
Guillaume's answer is essentially the same, and he submitted 4 minutes earlier while I was still typing; he should get the accepted answer. I'll leave mine here in case someone wants to reference the bitget solution.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!