Change if -statement by userinput

Is it possible to change an if condition by a User input? E.g. I have a dropdown menu with the options ('<','>') and an if condition (if i>5 ....) I want to adapt my if-condition to the selected option in the dropdown menu. So if I choose '<' in the dropdown menu, my if condition changes from (if i>5 to if i<5).

 Respuesta aceptada

Stephen23
Stephen23 el 5 de Oct. de 2018
Editada: Stephen23 el 5 de Oct. de 2018
Method one: use a cell array of function handles, and simply use the index from the menu to select which one you want:
idx = index of selection in menu, where 1='<' 2='>'
C = {@lt,@gt};
if C{idx}(i,5)
...
end
Method two: logical selection:
str = the selected string, either '<' or '>'
if strcmp(str,'>')&&(i>5) || strcmp(str,'<')&&(i<5)
...
end

4 comentarios

Matthias Berger
Matthias Berger el 5 de Oct. de 2018
Thank you a lot, the solution works just fine
John K. George
John K. George el 23 de Jun. de 2021
Hi Stephen,
Could you provide a more complete example? I am getting the following errors:
str = the selected string, either '<' or '>'
Error: Invalid expression. Check for missing multiplication operator, missing or
unbalanced delimiters, or other syntax error. To construct matrices, use brackets
instead of parentheses.
John K. George
John K. George el 23 de Jun. de 2021
Thank you!
A third approach, if you have a small fixed set of options:
% operator = input(['Enter the operator, either > or <, to be used ', ...
% 'in the comparison'], 's');
operator = '>'; % hard-coding this because you can't run INPUT in an Answers post
x = pi;
switch operator
case '>'
if x > 5
disp('x is greater than 5.')
else
disp('x is not greater than 5.')
end
case '<'
if x < 5
disp('x is less than 5.')
else
disp('x is not less than 5.')
end
otherwise
error(['I asked for either > or < and you entered ', operator, '.'])
end
x is not greater than 5.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Centro de ayuda y File Exchange.

Productos

Preguntada:

el 5 de Oct. de 2018

Comentada:

el 23 de Jun. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by