Equality of a numeric list using a string

6 ビュー (過去 30 日間)
Jason
Jason 2016 年 1 月 28 日
回答済み: Jason 2016 年 1 月 28 日
I have a set of values fwhm that I then remove valyes lower than Y20. However, I use this in many places and sometimes want values > Y20
T=fwhm(fwhm>Y20);
Is there a way to pass the string for the equality, where in the case above I could pass either '>Y20' or '<Y20'?
Thanks

採用された回答

Walter Roberson
Walter Roberson 2016 年 1 月 28 日
If Y20 is known at the time you decide whether you want > or <, then define a function:
selY20 = @(Var) Var(Var>Y20);
or
selY20 = @(Var) Var(Var<Y20);
depending on which one you want. Then your code would have
T = selY20(fwhm);
If you do not know Y20 at the time you make the decision, then at the time of the decision define a function
selY = @(Var, Y) Var(Var<Y);
or
selY = @(Var, Y) Var(Var>Y);
and code
T = selY(fwhm, Y20);
Or if you want to be more hard-core,
selY = @lt;
or
selY = @gt;
and code
T = fwhm(selY(fwhm, Y20));
A < B is the same internally as lt(A,B) and A > B is the same internally as gt(A,B)

その他の回答 (2 件)

Guillaume
Guillaume 2016 年 1 月 28 日
編集済み: Guillaume 2016 年 1 月 28 日
I'd recommend you use function handles rather than strings:
comparisons = {@gt, @lt}; %gt is the function name of >, lt is the function name of <
selectedcomparison = 1; %1 is <, 2 is >
T = fwhm(comparisons{selectedcomparison}(fwhm, Y20)) %note that the brackets after {...} is a function call
edit: if you really want to use strings:
comparisons = {'<', '>'};
selectedcomparison = 1; %1 is <, 2 is >
compfn = str2func((comparisons{selectedcomparison});
T = fwhm(compfn(fwhm, Y20))

Jason
Jason 2016 年 1 月 28 日
Thankyou Walter and Guillaume.

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by