Last active
August 29, 2015 14:08
-
-
Save hcc23/274b76edc3dd82d5de1a to your computer and use it in GitHub Desktop.
MATLAB script to compute a row-complete Latin square
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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