How to split a function according to their variables?
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
DGM
le 30 Sep 2021
Modifié(e) : DGM
le 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))
f_x1(x1) = sum(C(has(C,x1)))
f_x2(x2) = sum(C(has(C,x2)))
f_y1(y1) = sum(C(has(C,y1)))
f_y2(y2) = sum(C(has(C,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 commentaires
Plus de réponses (1)
Walter Roberson
le 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))
fx2 = mapSymType(f, "plus", @(X) SelectPlus(X, x2))
fy1 = mapSymType(f, "plus", @(X) SelectPlus(X, y1))
fy2 = mapSymType(f, "plus", @(X) SelectPlus(X, 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
Voir également
Catégories
En savoir plus sur Conversion Between Symbolic and Numeric dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!