Why am I getting an error that matrices must agree?

Working on this question about a Fence problem(Have to write a script about it) and here is my script:
prompt= 'State the Area: ';
Area = input(prompt,'s');
prompt= 'State the Straight Cost: ';
StrCo = input(prompt,'s');
prompt= 'State the Curved Cost: ';
CurCo = input(prompt,'s');
R = .01:.01:sqrt(2*Area/pi);
L = (Area - 1/2*pi*R.^2)/(2*R);
Cost = (2*L+ 2*R)*StrCo +pi*R*CurCo;
[BestCost,Index] = min(Cost);
BestR = R(Index);
BestL = L(Index);
disp(['The best cost is',num2str(min(Cost)),'.'])
disp(['The best radius is',num2str(BestR),'.'])
disp(['The best length is',num2str(BestL),'.'])
But when I go and run my script, I am so confused on why I get this error:
>> untitled3
State the Area: 1600
State the Straight Cost: 30
State the Curved Cost: 40
Error using -
Matrix dimensions must agree.
Error in untitled3 (line 10)
L = (Area - 1/2*pi*R.^2)/(2*R);

 Accepted Answer

Rik
Rik on 28 Feb 2018
Edited: Rik on 28 Feb 2018
The documentation states the following
str = input(prompt,'s') returns the entered text, without evaluating the input as an expression.
So your problem is that Area is still a char vector. You need to include the following line of code, just after input to convert the user response to an actual value.
Area=str2double(Area);
Edit: I see Torsten and Andrei have noticed another problem with this line of code: because R is a vector, the division must be element-wise as well.
prompt= 'State the Area: ';
Area = input(prompt,'s');
Area=str2double(Area);
prompt= 'State the Straight Cost: ';
StrCo = input(prompt,'s');
StrCo=str2double(StrCo);
prompt= 'State the Curved Cost: ';
CurCo = input(prompt,'s');
CurCo=str2double(CurCo);
R = .01:.01:sqrt(2*Area/pi);
L = (Area - 1/2*pi*R.^2)./(2*R);
Cost = (2*L+ 2*R)*StrCo +pi*R*CurCo;
[BestCost,Index] = min(Cost);
BestR = R(Index);
BestL = L(Index);
disp(['The best cost is',num2str(min(Cost)),'.'])
disp(['The best radius is',num2str(BestR),'.'])
disp(['The best length is',num2str(BestL),'.'])

2 Comments

The str2double function helped! My code went thought perfectly no problem thank you so much!!

Sign in to comment.

More Answers (2)

L = (Area - 1/2*pi*R.^2)./(2*R);
Best wishes
Torsten.
prompt= 'State the Area: ';
Area = input(prompt);
prompt= 'State the Straight Cost: ';
StrCo = input(prompt);
prompt= 'State the Curved Cost: ';
CurCo = input(prompt);
R = .01:.01:sqrt(2*Area/pi);
L = (Area - 1/2*pi*R.^2)./(2*R);
Cost = (2*L+ 2*R)*StrCo +pi*R*CurCo;
[BestCost,Index] = min(Cost);
BestR = R(Index);
BestL = L(Index);
disp(['The best cost is ',num2str(min(Cost)),'.'])
disp(['The best radius is ',num2str(BestR),'.'])
disp(['The best length is ',num2str(BestL),'.'])

Categories

Find more on Programming in Help Center and File Exchange

Asked:

on 28 Feb 2018

Edited:

on 28 Feb 2018

Community Treasure Hunt

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

Start Hunting!