I get Arrays have incompatible sizes for this operation with an elseif statement what do i do?
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Viktoriya
el 14 de Oct. de 2022
Editada: the cyclist
el 14 de Oct. de 2022
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 comentario
the cyclist
el 14 de Oct. de 2022
Editada: the cyclist
el 14 de Oct. de 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.
Respuesta aceptada
Jan
el 14 de Oct. de 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 comentarios
Más respuestas (2)
dpb
el 14 de Oct. de 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 comentarios
the cyclist
el 14 de Oct. de 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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!