Help with If else statements
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jared Johnson
el 5 de Dic. de 2015
I wrote a script that reads data from the internet and predicts the winner of a football game. The model I use assigns a total of 10 points to each team, so the closest win is 6-4 or a 5-5 draw. I display the winner of the game in the GUI with a text box with the code,
if true
% code
if TeamAScore > TeamBScore
set(handles.text4,'String', TeamAName);
else
set(handles.text4,'String', TeamBName);
end;
end
This works great, but I wanted to spruce it up by letting the user know how big the win is. So I wrote,
if true
%Display winner
WinBig = ' wins big.';
WinComfort = ' wins comfortably';
WinClose = ' wins close';
if TeamAScore >= 9
disp(TeamAName); %win big
NewName = [TeamAName, WinBig];
set(handles.text4,'String', NewName);
elseif TeamAScore == 8 || 7
disp(TeamAName); % comfortable win
NewName = [TeamAName, WinComfort];
set(handles.text4,'String', NewName);
elseif TeamAScore == 6
disp(TeamAName); % close win
NewName = [TeamAName, WinClose];
set(handles.text4,'String', NewName);
elseif TeamBScore >=9
disp(TeamBName); % win big
NewNameB = [TeamBName, WinBig];
set(handles.text4,'String', NewNameB);
elseif TeamBScore == 8 || 7
disp(TeamBName); % comfortable win
NewNameB = [TeamBName, WinComfort];
set(handles.text4,'String', NewNameB);
elseif TeamBScore == 6
disp(TeamBName); % close win
NewNameB = [TeamBName, WinClose];
set(handles.text4,'String', NewNameB);
elseif TeamBScore == TeamAScore
disp('Too close to call'); % too close to call
set(handles.text4,'String', 'Too close to call');
end;
% code
end
But this gives me TeamA everytime, not sure why. Any help is appreciated.
0 comentarios
Respuesta aceptada
Stephen23
el 5 de Dic. de 2015
Editada: Stephen23
el 5 de Dic. de 2015
Your first elseif is always going to be true. Why? Because you are ignoring MATLAB's rules of operator precedence. Check this out:
>> TeamAScore = 5;
>> TeamAScore == 8 || 7
ans =
1
Does this mean that 5 is equal to either seven or eight? Of course not, we just need to follow the basic operator precedence rules that we were taught in highschool (and shown in the link above), so we know that this code is really equivalent to:
>> (TeamAScore == 8) || 7
ans =
1
>> 0 || 7
ans =
1
where seven is true because it is non-zero. When you pay attention to the operator precedence rules then you would probably have written something like this:
>> TeamAScore == 7 || TeamAScore == 8
ans =
0
Or more compactly:
>> any(TeamAScore == [7,8])
ans =
0
0 comentarios
Más respuestas (1)
Image Analyst
el 5 de Dic. de 2015
This is incorrect syntax:
elseif TeamAScore == 8 || 7
You'd need this:
elseif TeamAScore == 8 || TeamAScore== 7
or, better and simpler:
elseif TeamAScore >= 7
Same problem for TeamBScore a little further down.
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!