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'
댓글 수: 0
답변 (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.
댓글 수: 0
이 질문은 마감되었습니다.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!