A=[randperm(4);randperm(4);randperm(4);randperm(4)];
n=0;

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

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

% rerun the program unless the conditions are fulfilled
while n~=8
A=[randperm(4);randperm(4);randperm(4);randperm(4)];
n=0;
end

A

    Source: geocities.com/hk/tamwingyin0415

               ( geocities.com/hk)