I get Arrays have incompatible sizes for this operation with an elseif statement what do i do?
19 ビュー (過去 30 日間)
古いコメントを表示
I have this code:
when i run it, it works with square as an input, but if i type rectangle or triangle i get this message;
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!