function [x_bin] = var_encode(x, bounds, N_gene) % VAR_ENCODE - Encodes the variables x in a binary representation % % Inputs: % x = [ number_of_samples x number_of_variables ] input matrix of variables to be encoded % bounds = [ number_of_variables x 2 ] input matrix where the ith row is the valid bounds for the ith variable % N_gene = number of bits used to encode a scalar representation % % Outputs: % x_bin = [ number_of_samples x N_var * N_gene ] binary encoding of each variable in x % % Written by: % -- % John L. Weatherwax 2006-08-28 % % email: wax@alum.mit.edu % % Please send comments and especially bug reports to the % above email address. % %----- % Check inputs: [N_samples,N_var] = size(x); assert( size(bounds,1)==N_var, 'bounds input must have N_var rows' ); assert( size(bounds,2)==2, 'bounds input must have two columns' ); % make sure all our initial input variables are within the required variables bounds before we encode them in binary: % x = enforce_bounds(x,bounds); % Compute the normalized variable values: % x_low = repmat( bounds(:,1), [1,N_samples] ).'; x_len = repmat( bounds(:,2) - bounds(:,1), [1,N_samples] ).'; x_norm = ( x - x_low ) ./ x_len; x_bin = []; for ii=1:N_var vars = x_norm(:,ii); % convert a column of variables at a time vars_bin = zeros(N_samples,N_gene); for mm=1:N_gene if( mm==1 ) vars_bin(:,mm) = ceil( x_norm(:,ii) - 2^(-mm) ); % 0 => means to the left of the boundary; 1 => to the right else Qm = ( 2.^( -(1:(mm-1)) ) ).'; vars_bin(:,mm) = ceil( x_norm(:,ii) - 2^(-mm) - vars_bin( :, 1:(mm-1) ) * Qm ); end end x_bin = [ x_bin, vars_bin ]; end