How can I create a loop that doesnt allow the same number to be input twice?

2 次查看(过去 30 天)
I have this code, that when passed a variable, creates a matrix and lets you input digits for a magic square
function magicsquare(M)
Code:
clc
[r,c] = size(M);
if (r ~= c)
disp('These are not the dimensions of a square!\n');
else
cSum = sum(M);
rSum= sum(M');
d1= sum(diag(M));
d2= sum(diag(fliplr(M)));
if(isequal(d1,d2,cSum(1),rSum(1)) && isequal(cSum,rSum))
fprintf('This square is magic!\n')
else
fprintf('This is not a magic square!\n')
end
end
end
How can I edit this to make it to where the user cannot input the same digit twice when inputting their numbers for the magic square?
Thanks

回答(1 个)

Walter Roberson
Walter Roberson 2019-4-18
if length(unique(M)) ~= numel(M)
error('You entered some number twice')
end

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by