I get Arrays have incompatible sizes for this operation with an elseif statement what do i do?
조회 수: 7 (최근 30일)
이전 댓글 표시
I have this code:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1156888/image.png)
when i run it, it works with square as an input, but if i type rectangle or triangle i get this message;
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1156893/image.png)
how do i fix it?
댓글 수: 1
the cyclist
2022년 10월 14일
편집: the cyclist
2022년 10월 14일
FYI, it is much better to paste in actual code, rather an image of code. In your case, it was easy to spot your error without needing to copy and run your code, but had that not been the case, it would have been annoying to have to re-type your code to test potential solutions.
It was great that you posted the entire error message and where it was occurring. That is very helpful.
채택된 답변
Jan
2022년 10월 14일
The == operator compare the arrays elementwise. Therefore the arrays on the left and right must have the same number of characters, or one is a scalar.
Use strcmp to compare char vectors instead.
if strcmp(shape, 'square')
Alternatively:
switch shape
case 'square'
case 'rectangle'
...
end
댓글 수: 0
추가 답변 (2개)
dpb
2022년 10월 14일
A character array is just an array of bytes; the length of 'square' is six characters while the 'rectangle' is 9 -- indeed, they are a mismatch of sizes.
There is one place in which such has been accounted for in a test -- and it is useful for exactly this purpose -- that is the switch, case, otherwise construct instead of if...end
shape=input('Please enter shape of interest: ','s');
switch lower(shape) % take out case sensitivity
case 'square'
...
case 'rectangle'
...
end
The case construct does an inherent match using strcmp(case_expression,switch_expression) == 1.
Alternatively, if you were to cast to the new string class, then it will support the "==" operator, but for such constructs as yours, the switch block is better syntax to use anyway.
Good luck, keep on truckin'... :)
댓글 수: 0
the cyclist
2022년 10월 14일
The essence of your issue is that you are using a character array as input. When character arrays are compared with the equality symbol (==), each character is compared in order. Because 'rectangle' and 'square' have different lengths, you get an error:
'square' == 'square'
'office' == 'square'
'rectangle' == 'square'
strcmp('square','square')
strcmp('office','square')
strcmp('rectangle','square')
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!