% Using a Hamming code with m=4;
% First, we construct the parity check matrix H
m=4;
H =[];
for j=1:2^m-1
cb = dec2bin(j,m);
for i=1:length(cb)
bv(i)=str2num(cb(i));
end
H = [H bv'];
end
H = sym(H)

% Taking the nullspace of H gives a matrix G whose rowspan is the linear
% code
nH = mod(null(H),2);
G = nH'
size(G)

% To pick a codeword m, we multiply G by a vector v in (Z_2)^11
v = [1 1 1 0 0 0 1 1 1 0 0]
m = mod(v*G,2)

% We can check that m is a codeword by multiplying by H
mod(H*m',2)

% Now we'll add an error to the message (in this example, in bit 9)
err(15)=0;
err(9) =1;

% The received message r will be the codeword m plus the err 
r = m + err;
r = sym(r)

% Now suppose that we have just received the word r and we want to correct
% any errors to get back to a codeword
% To do this we find the syndrome of the word r
syn = mod(H*r',2)

% Using slick code, we can find the number of the column of H that equals
% this syndrome -- this is the bit that needs correcting
badbit = bin2dec(int2str(int8(syn')))

% We make a vector e with a 1 in that position and 0's elsewhere
e(15)=0;
e(badbit)=1

% The corrected codeword is then r+e
cw = mod(r+e,2)

% We can check that this is a codeword by multiplying by H
mod(H*cw',2)

% Indeed, this is our original codeword m
cw - m

% To recover the length-11 vector v, we can solve the system v*G = cw for v
% Since G has a 11x11 identity matrix in columns 3, 5-7, and 9-15, it
% suffices to take those entries from the codeword. 

y = [cw(3) cw(5:7) cw(9:15)]

y-v