Is there any way to separate the terms of a product?

1 回表示 (過去 30 日間)
Hello,
Let's say I have this function_handle: f = @(x) exp(x-2)*log(x)
Is it possible to assign each function that comprises this product to its own seperate variable i.e:
g = exp()
h = x-2
j = log()
k = x
Thank you!
  2 件のコメント
John D'Errico
John D'Errico 2019 年 2 月 17 日
編集済み: John D'Errico 2019 年 2 月 17 日
Sure. Write your own expression parsing code.
f = @(x) exp(x-2)*log(x);
>> func2str(f)
ans =
'@(x)exp(x-2)*log(x)'
Panagiotis Panagopoulos Papageorgiou
Panagiotis Panagopoulos Papageorgiou 2019 年 2 月 18 日
Hello,
Seeing my question once more, I believe that I've not been specific enough.
In my programme I ask the user to enter his own function. Once that is done I'd like to "break" that function into seperate parts, and then assign each part to it's own variable. So if I input this:
exp(x-2)*log(x)
I want to get these variables:
g = exp(x)
h = x-2
j = log(x)
k = x
Thank you for your time and effort. :)

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

採用された回答

Walter Roberson
Walter Roberson 2019 年 2 月 17 日
If you have the Symbolic Toolbox, then
f = @(x) exp(x-2)*log(x)
syms x
temp = f(x);
op0 = feval(symengine, 'op', temp, 0)
rest = children(temp)
rest0 = arrayfun(@children, rest, 'uniform', 0)
and so on, taking op 0 and children each time. op 0 will be things like _mult and _plus for * and + (and subtraction -- subtraction is _plus of negative of the value).
With a little work, you could create a routine that broke expressions down into nested cell arrays or into nested struct.
This is not a nice interface, but it is all that is availabe in the symbolic toolbox in any released version.
  3 件のコメント
Walter Roberson
Walter Roberson 2019 年 2 月 18 日
I attached code that produces a nested cell parse tree. You could modify it.
The current last line has {op0} which will produce the token such as exp . You would want to look at length(rest) and use that many nominal variables similar to the representative_vars that I introduce near the beginning of the code to convert simple @functionname into functionname(x, y, z, ...) expressions.
Panagiotis Panagopoulos Papageorgiou
Panagiotis Panagopoulos Papageorgiou 2019 年 2 月 19 日
Awesome, thank you!

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

その他の回答 (0 件)

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by