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

 采纳的回答

Stephen23
Stephen23 2018-10-5
编辑:Stephen23 2018-10-5
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 个评论

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.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Programming 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by