function GG = gengray(N,K) % generate the N-ary Gray code of length K % taken from http://nr.stic.gov.tw/ejournal/ProceedingA/v22n6/841-848.pdf % http://en.wikipedia.org/wiki/Gray_code % Guan, Dah-Jyu. "Generalized Gray Codes with Applications." Proc. Katl. Sci. Counc. Repub. Of China (A) 22 (1998): 841-848. [5]. GG = []; g = []; u = []; n = []; for i=0:N g(i+1) = 0; u(i+1) = 1; n(i+1) = K; end while ~g(N+1) %for j=N-1:-1:0 % fprintf('%d',g(j+1)); %end str = ''; for j=N-1:-1:0 str = [str, num2str(g(j+1))]; end %fprintf('%s\n',str); GG(end+1) = base2dec(str,K); i = 0; k = g(1) + u(1); while ( (k>=n(i+1)) | (k<0) ) u(i+1) = -u(i+1); i = i+1; k = g(i+1) + u(i+1); end g(i+1) = k; end return