I get Arrays have incompatible sizes for this operation with an elseif statement what do i do?
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Viktoriya
am 14 Okt. 2022
Bearbeitet: the cyclist
am 14 Okt. 2022
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 Kommentar
the cyclist
am 14 Okt. 2022
Bearbeitet: the cyclist
am 14 Okt. 2022
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.
Akzeptierte Antwort
Jan
am 14 Okt. 2022
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 Kommentare
Weitere Antworten (2)
dpb
am 14 Okt. 2022
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 Kommentare
the cyclist
am 14 Okt. 2022
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 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!