필터 지우기
필터 지우기

Why doesn't this work?

조회 수: 3 (최근 30일)
Collin Kerr
Collin Kerr 2016년 4월 1일
댓글: Star Strider 2016년 4월 2일
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.
  댓글 수: 1
Collin Kerr
Collin Kerr 2016년 4월 2일
also I did not type in the ' with sum(x)~=g it should be sum(x')'~=g'

댓글을 달려면 로그인하십시오.

채택된 답변

Star Strider
Star Strider 2016년 4월 2일
편집: Star Strider 2016년 4월 2일
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.
  댓글 수: 2
Collin Kerr
Collin Kerr 2016년 4월 2일
Im trying to tell the code if the sum of x does not equal the sum of f then display (the error message), but if they are the same as f then keep going.
Star Strider
Star Strider 2016년 4월 2일
If you want the sum of a all the elements of a (4x4) (or any other array), the easiest way is:
f = sum(M(:));
in that syntax, ‘g’ is going to be the same, so only one comparison would be necessary.
Since all the row, column and diagonal sums are going to be equal in a magic matrix, you would have to test that all the row, column, and diagonal sums are equal, that is all are the same, for the matrix to be magic. (You may not have to test for all of those. I leave that choice to you.) This is not the same as the sum of all the elements in the matrix being equal to the sum of all the elements in a magic matrix being the same. Only the individual row, column, and diagonal sums matter.
To illustrate, run this:
Mg = magic(4);
q3 = sum(Mg)
q4 = sum(Mg,2)
q5 = sum(diag(Mg))

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by