Input and help with if-else structure

1 view (last 30 days)
Adel
Adel on 28 Feb 2014
Answered: Jan on 28 Feb 2014
I am attempting to write a code using an if else statement shown below. I was curious as to why matlab outputs an error (also shown below) when the number of characters don't match each other for the variable "today". The program code runs if the number of characters where equivalent for both "today" variables but otherwise the program won't run. Any clue as to why this occurs and how I can solve this problem? Thank you. I was also attempting to make it so that the user can input the weather via an input statement asking 'What is the weather like today?' and then having the program run.
%%
today = 'snow day'
if today == 'sunny day'
disp('YAY :)')
else
disp('I wish it were sunny :(')
Error using == Matrix dimensions must agree. end

Answers (1)

Jan
Jan on 28 Feb 2014
The== operator compares arrays elementwise. Strings are vectors of type char. When the two operands of == have different numbers of elements, a comparision is not possible, except if one is a scalar.
Use strcmp instead to compare strings:
if strcmp(today, 'sunny day')

Community Treasure Hunt

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

Start Hunting!