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 .

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

 采纳的回答

"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'

更多回答(2 个)

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 个评论

Thank you very much . it works. But i cant see the item for acceptance of this answer. that is strange. I saw it before but now I can not. Do you know how I can do it? Thanks.
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.
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.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by