Info

此问题已关闭。 请重新打开它进行编辑或回答。

Matrix dimensions must agree error, confused because it works sometimes and I don't even have a matrix as far as I know.

1 次查看(过去 30 天)
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!

回答(1 个)

James Heselden
James Heselden 2019-10-31
编辑:James Heselden 2019-11-1
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)
In your type of situation; it is often better to use the Switch Statement.
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 个评论
Rik
Rik 2019-11-1
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.

此问题已关闭。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by