% generate a 9x9 matrix with entries 1 to 9
A=ceil(9*rand(9));
n=0;

% check for the rows
for r=1:9;
if sum(A(r,:))==45 & sum(A(r,:).^2)==30
n=n+1;
end
end

% check for the columns
for s=1:9;
if sum(A(:,s))==45 & sum(A(:,s).^2)==30
n=n+1;
end
end

% check for the small squares
for k=1:3;
for l=1:3;
if sum(sum(A(3*k-2:3*k,3*l-2:3*l)))==45 & sum(sum(A(3*k-2:3*k,3*l-2:3*l).^2))==30
n=n+1;
end
end
end

% rerun the program unless the conditions are fulfilled
while n~=27
A=ceil(9*rand(9));
n=0;
end
A

    Source: geocities.com/hk/tamwingyin0415

               ( geocities.com/hk)