Clear Filters
Clear Filters

I get Arrays have incompatible sizes for this operation with an elseif statement what do i do?

8 views (last 30 days)
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 Comment
the cyclist
the cyclist on 14 Oct 2022
Edited: the cyclist on 14 Oct 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.

Sign in to comment.

Accepted Answer

Jan
Jan on 14 Oct 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

More Answers (2)

dpb
dpb on 14 Oct 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'... :)

the cyclist
the cyclist on 14 Oct 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'
ans = 1×6 logical array
1 1 1 1 1 1
'office' == 'square'
ans = 1×6 logical array
0 0 0 0 0 1
'rectangle' == 'square'
Arrays have incompatible sizes for this operation.
You could instead use the strcmp function to check
strcmp('square','square')
strcmp('office','square')
strcmp('rectangle','square')

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!