How to split a function according to their variables?

22 views (last 30 days)
Hi. I want to split function according to their variables.
For example
f(x1,x2,y1,y2) = 10*x1 + 20*x2 + 10*y1 + 10*y2 ;
And I want to split like below.
f(x1) = 10*x1 ;
f(x2) = 20*x2 ;
f(y1) = 10*y1 ;
f(y2) = 20*y2 ;
Please help me...!
  2 Comments
KSSV
KSSV on 29 Sep 2021
Already you have done it....what else you want?
연승 김
연승 김 on 30 Sep 2021
I think I gave a wrong example.... sorry about it.
If there is a more complecated function, how can I do this automatically??
It means I don't have to code the function f(x1), f(x2), f(y1), f(y2) each one by one.
f(x1,x2,y1,y2) = 10*x1 + 20*x2 + 10*y1 + 10*y2 + log(x1) + 1/x1 + 1/y1 ;
f(x1) = 10*x1 + log(x1) + 1/x1 ;
f(x2) = 20*x2 ;
f(y1) = 10*y1 + 1/y1 ;
f(y2) = 20*y2 ;

Sign in to comment.

Accepted Answer

DGM
DGM on 30 Sep 2021
Edited: DGM on 30 Sep 2021
There's probably a better way, but I never really use symbolic stuff. I'll just throw this out there. I renamed the functions just for clarity purposes in the scope of this example.
syms x1 x2 y1 y2
fparent(x1,x2,y1,y2) = 10*x1 + 20*x2 + 10*y1 + 10*y2 + log(x1) + 1/x1 + 1/y1;
C = cell2sym(children(fparent))
C = 
f_x1(x1) = sum(C(has(C,x1)))
f_x1(x1) = 
f_x2(x2) = sum(C(has(C,x2)))
f_x2(x2) = 
f_y1(y1) = sum(C(has(C,y1)))
f_y1(y1) = 
f_y2(y2) = sum(C(has(C,y2)))
f_y2(y2) = 
If you're using something older than R2020b, you'll have to remove the cell2sym() call.
Mind you, this all assumes that the expression is a simple sum (hence the use of sum() to reconstruct the subexpressions). What's supposed to happen if the function expression is something like this?
fparent(x1,x2,y1,y2) = exp(x1*sin(log(x2)))/(y1*x1 + atan(y2));
  2 Comments
Walter Roberson
Walter Roberson on 30 Sep 2021
DGM's use of has() is better than what I came up with.
연승 김
연승 김 on 30 Sep 2021
Thank you for your kind!!
C = cell2sym(children(fparent))
This code works well^^

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 30 Sep 2021
syms x1 x2 y1 y2
f(x1,x2,y1,y2) = 10*x1 + 20*x2 + 10*y1 + 10*y2 + log(x1) + 1/x1 + 1/y1 ;
fx1 = mapSymType(f, "plus", @(X) SelectPlus(X, x1))
fx1(x1, x2, y1, y2) = 
fx2 = mapSymType(f, "plus", @(X) SelectPlus(X, x2))
fx2(x1, x2, y1, y2) = 
fy1 = mapSymType(f, "plus", @(X) SelectPlus(X, y1))
fy1(x1, x2, y1, y2) = 
fy2 = mapSymType(f, "plus", @(X) SelectPlus(X, y2))
fy2(x1, x2, y1, y2) = 
function selected = SelectPlus(Expression, var)
ch = children(Expression);
selected_ch = ch(cellfun(@(X) ismember(var, symvar(X)), ch));
selected = sum([selected_ch{:}]);
if isempty(selected); selected = sym(0); end
end

Community Treasure Hunt

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

Start Hunting!