Error Marix dimensions must agree.

조회 수: 1 (최근 30일)
dylan stephens
dylan stephens 2021년 3월 7일
답변: Walter Roberson 2021년 3월 7일
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;

답변 (1개)

Walter Roberson
Walter Roberson 2021년 3월 7일
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

카테고리

Help CenterFile Exchange에서 Marine and Underwater Vehicles에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by