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'

回答 (1 件)

Stephen23
Stephen23 2018 年 10 月 5 日
編集済み: Stephen23 2018 年 10 月 5 日

2 投票

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.

この質問は閉じられています。

質問済み:

2018 年 10 月 5 日

閉鎖済み:

2021 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by