필터 지우기
필터 지우기

How do I create a 2^n by n matrix that the rows of the matrix enumerate all the possibilities for a n digit binary number?

조회 수: 2 (최근 30일)
For example, for n=3, there are 8 rows, and they are 000,100,010,001,110,101,001,111 (may not in this order). Any fast way to realize it using a function, say f(n)?

채택된 답변

Guillaume
Guillaume 2016년 2월 11일
Use dec2bin to get the string representation. Subtract '0' from the string to convert characters '0' and '1' to numbers 0 and 1:
n = 3;
dec2bin(0:pow2(n)-1) - '0'
  댓글 수: 2
Shawn Miller
Shawn Miller 2016년 2월 11일
Thanks Guillaume, could you explain a bit why a string minus another string '0' would convert a string to a number? Also, why even you didn't provide the second parameter (n in dec2bin(d,n)) in dec2bin() function, you still get 3-digit numbers?
Guillaume
Guillaume 2016년 2월 11일
편집: Guillaume 2016년 2월 11일
In matlab, when you subtract one character from another, you are in effect subtracting the ASCII values of the character. So, obviously ASCII of '0' - ASCII of '0' is 0. Since '1' follows '0' in the ASCII table. ASCII of '1' - ASCII of '0' is 1. In fact, ASCII of any 'digit' - ASCII of '0' is that digit.
dec2bin will always return strings padded to the minimum number of bits to represent the greatest input. Since you need 3 bits to represent the 4 to 7 of the input array, all strings are returned with 3 bits.
You could have specified the number of bits explicitly if you wanted.

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

추가 답변 (1개)

Jan
Jan 2016년 2월 11일
A fast version: FEX: VChooseKRO
r = VChooseKRO(uint8(0:1), 3);
  댓글 수: 2
Shawn Miller
Shawn Miller 2016년 2월 11일
편집: Shawn Miller 2016년 2월 11일
I downloaded the VChooseKRO function but how do I set up this file? I transfered the two .m files into MATLAB path but doesn't work?
Guillaume
Guillaume 2016년 2월 11일
You'll have to compile the c code into a mex file. If you don't care for speed (if your n is not huge, speed is not an issue) you may be better off with some of the file exchange submission mentioned by VChooseKRO, or use my solution which has no dependency.

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by