Matrix dimensions must agree. Error while using if.
Info
This question is closed. Reopen it to edit or answer.
Show older comments
%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'
Answers (1)
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.
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!