How to calculate the syms with variable has the same name?

1 回表示 (過去 30 日間)
wei zhang
wei zhang 2020 年 6 月 10 日
回答済み: Stephen23 2020 年 6 月 10 日
Hello,
I am writing a function with an augument to receive some expression, like ' a>0', ' b<0' and 'a>0&b<0'. There are variables named as "a" and "b" in the function's workspace. The augument to receive the expression is char class. How could I to calculate this expression in the function? Must I use "eval"? I have got a suggestion that I should not use "eval". I thought I could turn the char expression to syms with "str2sym". What should I do next? Thank you.
function myfun(exp,a,b)
% e.g. exp= 'a>0';
% 1st way : eval(exp)
% 2nd way(I prefer):
% exp1 = str2sym(exp);
% I don't know what to do next
end

回答 (1 件)

Stephen23
Stephen23 2020 年 6 月 10 日
function out = myfun(exp,a,b)
fun = str2func(sprintf('@(a,b)%s;',exp));
out = fun(a,b);
end
Tested:
>> myfun('a>0',3,2)
ans = 1
>> myfun('a>0&&b<0',3,2)
ans = 0

カテゴリ

Help Center および File ExchangeFormula Manipulation and Simplification についてさらに検索

タグ

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by