MATLAB Answers

Why Does My Code Work for Fprintf, but not disp() for outputting a result from the user input

3 views (last 30 days)
Ronin Gick
Ronin Gick on 25 Oct 2019
Commented: Cris LaPierre on 25 Oct 2019
Hello, I recently was using MatLab and ran into an error consistently that was
"Error using +
Matrix dimensions must agree.
Error in GickRonin_M2_Ch5_part2 (line 39)
disp('Fish caught for WholeFish: ' + WholeFish + 'kg, sold for: ' + WFPrice) "
Here is the code (Jist of it user inputs amount of fish caught, then the weights of the fish depending on weight that is the 'grade' and the 'grade' impacts the $)
This is before I changed the final statement to fprintf
EndIndex = input("What is the # of Fish you have caught? ");
x = 1;
Fish = (1:EndIndex);
while (x <= EndIndex)
Fish(x) = input('Weight of fish = ');
x = x + 1;
end
WholeFish = 0;
Fillet = 0;
Canning = 0;
PetFood = 0;
FishExtracts = 0;
% Loop to check for what weight the fish is and assign it to the correct
% Class of Fish
for Weight = Fish
if (Weight > 30)
WholeFish = WholeFish + Weight;
elseif (Weight > 20 && Weight <= 30)
Fillet = Fillet + Weight;
elseif (Weight > 10 && Weight <= 20)
Canning = Canning + Weight;
elseif (Weight > 5 && Weight <= 10)
PetFood = PetFood + Weight;
elseif (Weight <=5)
FishExtracts = FishExtracts + Weight;
end
end
disp (WholeFish)
%Display the Weights of each weight class as well as the price
WFPrice = WholeFish * 20;
FPrice = Fillet * 15;
CPrice = Canning * 6;
PFPrice = PetFood * 4;
FEPrice = FishExtracts;
TotalPrice = WFPrice + FPrice + CPrice + PFPrice + FEPrice;
%Checking my variables
disp ("FishWF: " + WFPrice)
disp('Fish caught for WholeFish: ' + WholeFish + ' kg, Sold for: ' + WFPrice)
Following me inputting only above 30 lb fish to check it would output the error above,
I then changed the code to
fprintf(' ,%d',WholeFish) and it outputted fine, I am confused as why this is happening.

  0 Comments

Sign in to comment.

Answers (1)

Cris LaPierre
Cris LaPierre on 25 Oct 2019
Concatenation with + only works for strings ("string"), not character arrays ('character array').
Replace your single quotes with double quotes in your disp command and it will work.
disp("Fish caught for WholeFish: " + WholeFish + "kg, Sold for: " + WFPrice)

  1 Comment

Cris LaPierre
Cris LaPierre on 25 Oct 2019
There are other issues with the code, however.
For example, your for loop. You must loop through the values one at a time.
for loop = 1:length(Fish)
Weight = Fish(loop)
if...
...
end
end

Sign in to comment.

Sign in to answer this question.