# Using AND Operator in “if” statements

조회 수: 5,464(최근 30일)
Andrew 2011년 5월 10일
편집: MathWorks Support Team 2020년 9월 2일
Hi,
When I type the following code:
if size([1 2 3])==size([4 5 6]) & size([4 5 6])==size([7 8 9])
'yes'
else
'no'
end
MATLAB Code Analyzer issues this warning message: "When both arguments are numeric scalars, consider replacing & with && for performance."
So, I use && instead of &:
if size([1 2 3])==size([4 5 6]) && size([4 5 6])==size([7 8 9])
'yes'
else
'no'
end
But when I run the updated script, MATLAB displays an error message in the Command Window:
??? Operands to the || and && operators must be convertible to logical scalar values.
What can I do to fix this? Thanks in advance.
Andrew DeYoung
Carnegie Mellon University
##### 댓글 수: 7표시숨기기 이전 댓글 수: 6
Jenny 2016년 8월 2일
Matt, I still use my notes from your class, and thanks for the help in this question. I needed to get this right.

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

### 채택된 답변

Andrew Newell 2011년 5월 10일
The problem is that size returns a vector:
size([1 2 3])
ans =
1 3
if numel([1 2 3])==numel([4 5 6]) && numel([4 5 6])==numel([7 8 9])
disp('yes')
else
disp('no')
end
Or you could use all(size([1 2 3])==size([4 5 6]) etc.
I have also put in the disp commands to take care of the other warnings.
##### 댓글 수: 1표시숨기기 없음
Andrew 2011년 5월 10일
Thanks!

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

### 추가 답변(1개)

Sean de Wolski 2011년 5월 10일
As an addendum to Andrew's thorough and good solution, you can check the sizes directly:
if(isequal(size([1 2 3]),size([4 5 6])))
disp('yes')
else
disp('no')
end
This will fail if the sizes are not the same but the number of elements (numel) is:
if(isequal(size([1 2 3]),size([4; 5; 6])))
disp('yes')
else
disp('no')
end
##### 댓글 수: 3표시숨기기 이전 댓글 수: 2
Andrew Newell 2011년 5월 10일
Good point.

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

### Community Treasure Hunt

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

Start Hunting!