Skip to content

Instantly share code, notes, and snippets.

@hcc23
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hcc23/274b76edc3dd82d5de1a to your computer and use it in GitHub Desktop.
Save hcc23/274b76edc3dd82d5de1a to your computer and use it in GitHub Desktop.
MATLAB script to compute a row-complete Latin square
function L = rowCompleteLatinSquare(n)
%% ROWCOMPLETELATINSQUARE Compute a row-complete Latin square of order n.
% Note: n must be even and greater than zero.
%
% This function follows
% http://personal.maths.surrey.ac.uk/st/H.Bruin/MMath/LatinSquares.html
% to which I have been pointed to from
% https://math.stackexchange.com/q/991078
%
if n<=0 || mod(n,2)~=0
error('n must be even and greater than zero.');
end
% create difference vector
d = 1:n-1;
for i= 2:2:(n-1)
d(i)=n-i;
end
clear i;
% preallocate memory
L = zeros(n,n);
% initialize first column
L(:,1) = (0:n-1)';
% populate Latin square
for i=2:n
L(:,i) = mod(L(:,i-1)-d(i-1),n);
end
% normalize (match order in first row and first column)
L = L(L(1,:)+1,:);
% reduce form (remap the symbols so that they are in natural order)
L_reduced = zeros(n,n);
for i=0:n-1
L_reduced(L==L(i+1,1))=i;
end
L = L_reduced;
clear L_reduced i;
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment