grey code generator in matlab

Here's an implementation of a Grey code generator in MATLAB:

main.m
function gc = grey_code(n)
    if n==1
        gc = [0 1];
    else
        gc_sub = grey_code(n-1);
        gc = [zeros(size(gc_sub)); flipud(gc_sub) + 2^(n-1)];
    end
end
175 chars
9 lines

This function takes an input n, which specifies the length of the Grey code sequence to be generated, and returns a Grey code sequence of length 2^n. The implementation is recursive, with the base case for n=1 generating the two-bit Grey code sequence [0 1].

The general method is to generate the n-1 bit Grey code sequence, duplicate it and append a 0 to the bottom half and a 1 to the top half, then concatenate the two halves.

For example, if n=3, we first generate the two-bit Grey code sequence [0 1], then create the four-bit sequence [00 01 11 10] by duplicating and appending 0 and 1 as described above.

Here's an example usage of the function:

main.m
>> gc = grey_code(3)
gc =
     0
     1
     3
     2
     6
     7
     5
     4
82 chars
11 lines

Note that the output is a column vector of uint integers. The binary representation of these integers is the generated Grey code sequence.

related categories

gistlibby LogSnag