MATLAB: Doesn’t this work

magicmathnotsum

clc,clear
prompt = 'Give a matrix of 4x4: ';
x = input(prompt);
[m,n] = size(x);
M=magic(4);
f=sum(M);
g=sum(M')';
if m~=4 | n~= 4
disp('The matrix is not a 4x4 please start again and fix the error.')
else
for i=1:16
if x(i)<=0
disp('Error one of the numbers put in was either a zero or negative, Fix it and start over.')
if sum(x)~=f && sum(x)~=g
disp('This is not a magic matrix, please start over, and do it right. ')
end
end
end
end
disp(x)
disp(sum(x))
disp(sum(x')')
Made a some changes to make it a bit easier, my question is basically why does 'sum(x)~=f && sum(x)~=g' not seem to be working, 4x4s that arent magic(4) seem to still be getting passed, and not denied.

Best Answer

Since ā€˜xā€™ is a matrix, you need to use either any, all, sum or some other function that produces the appropriate scalar.
Consider:
x = 1:4;
f = 2;
q = x~=f
q =
1 0 1 1
What do you want the comparison to do? Iā€™m certain it would like to know!
EDIT ā€” When you evaluate:
f=sum(M);
g=sum(M')';
they are still going to be (1x4) vectors.