Info
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
Matrix dimensions must agree error, confused because it works sometimes and I don't even have a matrix as far as I know.
조회 수: 4 (최근 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!
댓글 수: 0
답변 (1개)
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)
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
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!