MATLAB Answers

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

Asked by Mr Robot

### Mr Robot (view profile)

on 18 Apr 2019
Latest activity Answered by Walter Roberson

### Walter Roberson (view profile)

on 18 Apr 2019
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

#### 0 Comments

Sign in to comment.

## 1 Answer

### Walter Roberson (view profile)

Answer by Walter Roberson

### Walter Roberson (view profile)

on 18 Apr 2019

if length(unique(M)) ~= numel(M)
error('You entered some number twice')
end

#### 0 Comments

Sign in to comment.