using operators (+,-,*,/) in variables

Hi, if i need to config for + to be 'op' for example how can i then use it as an actual + further down the code?
example
op='+';
a=1;
b=2;
c=a(+ as op)b;

 採用された回答

Guillaume
Guillaume 2014 年 12 月 3 日

0 投票

Use str2fun to change your string into a function handle. Note that the string content must be a valid matlab function name ( '+' is)
op = '+';
a = 1;
b = 2;
opfn = str2fun(op);
c = opfn(a, b);
There is no way to have it
c = a opfn b; %can't be done in matlab

2 件のコメント

Guillaume
Guillaume 2014 年 12 月 3 日
Note that if you don't require to start with a string, you could just define opfn as:
opfn = @plus; %@minus, @times, @rdivide for elementwise -, *, / respectively
Sean de Wolski
Sean de Wolski 2014 年 12 月 3 日
Use this approach of opfun = @plus or whatever.

サインインしてコメントする。

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 12 月 3 日

0 投票

You can create this function
function y=op(a,b,operator)
if operator=='+'
y=a+b
elseif operator=='-'
y=a-b
elseif operator=='/'
y=a/b
elseif operator=='*'
y=a*b
end
% And call it
y=op(5,6,'+')

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

タグ

質問済み:

2014 年 12 月 3 日

回答済み:

2014 年 12 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by