Balanced Latin squares

A latin square is an N x N matrix in which every row and column contains exactly one of each of N elements. If the square is balanced, every element is followed and preceded exactly once by each other element.

The following Matlab script generates random balanced latin squares.

function L = latin(N)

while 1 == 1,
    L = zeros(N, N);
    L(1, 1:N) = randperm(N);
    
    for i = 1:N,
        for j = 1:N,
            if L(i, j) ~= 0,
                continue;
            end;
            allowed = 1:N;
            for test = 1:N,
                if ~isempty(find(L(i, :) == allowed(test))),
                    allowed(test) = 0;
                    continue;
                elseif ~isempty(find(L(:, j) == allowed(test))),
                    allowed(test) = 0;
                    continue;
                else,
                    for k = 1:i,
                        el = find(L(k, :) == allowed(test));
                        if el > 1 & j > 1,
                            if L(i, j - 1) == L(k, el - 1),
                                allowed(test) = 0;
                            end;
                        end;
                    end;
                end;
            end;
            allowed(find(allowed == 0)) = [];
            if ~isempty(allowed),
                L(i, j) = allowed(1);
            end;
        end;
    end;
    if isempty(find(L == 0)),
        break;
    end;
end