Matrix dimensions must agree. Error while using if.

%example
shape=input('What shape do you want?','s');
if shape=='square'
side=input('What is the length of one side?');
area=side^2;
fprintf('The area is %f\n',area')
elseif shape=='rectangle'
length=input('What is the length?');
width=input('What is the width?');
area=length*width;
fprintf('The area is %f\n',area')
end
(after running the program it says:)
What shape do you want?rectangle
Matrix dimensions must agree.
Error in untitled (line 2) if shape=='square'

Risposte (1)

Stephen23
Stephen23 il 5 Ott 2018
Modificato: Stephen23 il 5 Ott 2018
Use strcmp or strcmpi to compare the character vectors:
strcmpi(shape,'square')
Or switch:
switch lower(shape)
case 'square'
...
case 'rectangle'
...
end
When you use == on character vectors it performs an element-wise comparison, i.e. it compares like this:
shape(1)=='s'
shape(2)=='q'
shape(3)=='u'
...
and you can see the problem when it gets to the 'g' of 'rectangle':
shape(7)==???
because the sizes of the two vectors do NOT match, so this is an error.

Questa domanda è chiusa.

Chiuso:

il 20 Ago 2021

Community Treasure Hunt

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

Start Hunting!

Translated by