Error Marix dimensions must agree.

2 visualizaciones (últimos 30 días)
dylan stephens
dylan stephens el 7 de Mzo. de 2021
Respondida: Walter Roberson el 7 de Mzo. de 2021
I am attempting to run this simulation 100,000 times to get an average amount of turns that can be played before the player loses the game. However after i inserted my for loop i received an error stating
Matrix dimensions must agree.
Error in untitled (line 36) if color == 'red'
if i remove the for loop the program runs fine but i need the while loop to iterate 100000 times.
any help would be much appreciated.
%General Housekeeping
clear all
clc
money=100;
bet=10;
color=input('Place your bet on red or black: ','s');
j=0;
sum=0;
for ii = 1:100000
i=0;
while money >= 0
r=randi([0 36]);
if r == 0
fprintf('The ball lands on green.\nYou lose your bet.\n\n')
money=money-bet;
elseif mod(r,2) == 0
if color == 'red'
fprintf('The ball lands on %g which is black.\nYou lose.\n\n',r);
money=money-bet;
elseif color == 'black'
fprintf('The ball lands on %g which is black.\nYou win.\n\n',r);
money=money+bet;
end
else
if color == 'red'
fprintf('The ball lands on %g which is red.\nYou win.\n',r);
money=money+bet;
elseif color == 'black'
fprintf('The ball lands on %g which is black.\nYou lose.\n',r);
money=money-bet;
end
end
i=i+1;
end
sum=sum+i;
j=j+1;
end
average=sum/j;

Respuestas (1)

Walter Roberson
Walter Roberson el 7 de Mzo. de 2021
input() with the 's' option returns a character vector. Character vectors are vectors of characters, where characters are effectively uint16() -- numbers really. So when you use == between a character vector and a constant, you are doing a vector comparison, same as if you had asked
if [114 101 100] == [98 108 97 99 107] %if 'red' == 'black'
which of course is a matrix dimension mismatch.
You need to use strcmp() or strcmpi(), or else you need to switch to using string() objects -- the == operator for string objects does do string comparison.
if 'red' == "black" %double quotes make it a string object

Categorías

Más información sobre Just for fun en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by