Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

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

1 visualización (últimos 30 días)
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!

Respuestas (1)

James Heselden
James Heselden el 31 de Oct. de 2019
Editada: James Heselden el 1 de Nov. de 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)
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 comentario
Rik
Rik el 1 de Nov. de 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.

La pregunta está cerrada.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by