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 日間)
Justin Kingman
Justin Kingman 2019 年 10 月 31 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
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