File Exchange

## dec2gc.m

version 1.0 (1.54 KB) by

This function converts a decimal number to its equivalent gray code representation

Updated

The function dec2gc converts a real positive numeric column vector to its gray code equivalent with a specified level of precision.

Example:
real_num = [34;78;123;7];%set of real numbers to be converted
N = 7;%precision level for gray coding
gray_code = dec2gc(real_num,N);

Result:
gray_code =

0 1 1 0 0 1 1
1 1 0 1 0 0 1
1 0 0 0 1 1 0
0 0 0 0 1 0 0

NOTE: N should be carefully chosen such that 2^N > max(dec)

Dmitri M

### Dmitri M (view profile)

Darshong Chen.

Nice solution.

I used it for building sequency of Hadamard matrix of order N.

Something like:

function SeqOrd = GetSequency( N )

% N - [in] the order of Hadamard matrix
% SeqOrd - [out] the sequency, so that SeqOrd[i] is the sequency of row i
%
% Algorithm:
% 1. build a list of indexes 0..N-1
% 2. convert order of bits of each index
% 3. get the gray code value for each index ( that was converted)
% This gives the needed permutation with indexes range [0 .. N-1]

v = bitrevorder((0:N-1)'); % build list and reverse bit-order

SeqOrd = bitxor(v,bitshift(v,-1)); % find the gray-code

end

Good Solution

Cathy Williams

can we convert a matrix? yeh whatever, served the purpose for me!

Darshong Chen,

Excellent solution. Thanks!

darnshong Chen

why not do like this:
numout=bitxor(numin,bitshift(numin,-1));

not need to loop.

##### MATLAB Release
MATLAB 6.5.1 (R13SP1)
##### Acknowledgements

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.