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).

 Risposta accettata

Stephen23
Stephen23 il 5 Ott 2018
Modificato: Stephen23 il 5 Ott 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 Commenti

Thank you a lot, the solution works just fine
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.
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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Programming in Centro assistenza e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by