Info
This question is closed. Reopen it to edit or answer.
Matrix dimensions must agree error, confused because it works sometimes and I don't even have a matrix as far as I know.
1 view (last 30 days)
Show older comments
So I have to code a game in matlab and I'm making a text based adventure RPG kind of thing, so I'm making demo codes for figuring out how to make attack mechanics.
clc
clear
attack1 = input('Choose your attack: \nPunch\nKick\n\n>>', 's');
critchance = randi(100);
damage = 0;
if attack1 == 'Punch'
damage = randi(20)+30;
if critchance >= 80;
damage = 2*damage;
end
elseif attack1 == 'Kick'
damage = randi(65)+15;
elseif attack1 == 'Call him ugly'
damage = 1000;
else
fprintf('That attack doesnt work!')
end
fprintf('Your attack did %.0f damage!',damage)
When I input Punch it works perfectly, but when I do Kick or anything else it says theres in error in the " if attack1 == 'Punch' " Line because the matrix dimensions don't agree. Thanks for any help!
0 Comments
Answers (1)
James Heselden
on 31 Oct 2019
Edited: James Heselden
on 1 Nov 2019
Simple solution: for your if/ifelse conditions you are using char arrays, swap these out to strings by replacing:
% e.g. replace
'Punch'
% with
"Punch"
So your code becomes:
clc
clear
attack1 = input('Choose your attack: \nPunch\nKick\n\n>>', 's');
critchance = randi(100);
damage = 0;
if attack1 == "Punch"
damage = randi(20)+30;
if critchance >= 80;
damage = 2*damage;
end
elseif attack1 == "Kick"
damage = randi(65)+15;
elseif attack1 == "Call him ugly"
damage = 1000;
else
fprintf('That attack doesnt work!')
end
fprintf('Your attack did %.0f damage!',damage)
clc
clear
attack1 = input('Choose your attack: \nPunch\nKick\n\n>>', 's');
critchance = randi(100);
damage = 0;
switch attack1
case 'Punch'
damage = randi(20)+30;
if critchance >= 80;
damage = 2*damage;
end
case 'Kick'
damage = randi(65)+15;
case 'Call him ugly'
damage = 1000;
otherwise
fprintf('That attack doesnt work!')
end
fprintf('Your attack did %.0f damage!',damage)
Good luck and on a side note, don't forget to add a \n to the end of a fprintf to make the output a bit cleaner.
Regards
James
1 Comment
Rik
on 1 Nov 2019
Another solution is to use strcmp to compare two char arrays. The reason for the error is that a char array (single quotes) is an array of characters, while a string scalar (double quotes) can contain multiple characters.
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!