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 日

0 投票

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 件のコメント

Matthias Berger
Matthias Berger 2018 年 10 月 5 日
Thank you a lot, the solution works just fine
John K. George
John K. George 2021 年 6 月 23 日
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 2021 年 6 月 23 日
Thank you!
Steven Lord
Steven Lord 2021 年 6 月 23 日
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 ExchangeProgramming についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by