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

 Accepted Answer

Stephen23
Stephen23 on 5 Oct 2018
Edited: Stephen23 on 5 Oct 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 Comments

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

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!