File Exchange

image thumbnail

dec2gc.m

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

6 Downloads

Updated

No License

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)

Comments and Ratings (5)

Dmitri M

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

Ricardo Salgado

Good Solution

Cathy Williams

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

Damon Bradley

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)

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

» Watch video