필터 지우기
필터 지우기

How to split a function according to their variables?

조회 수: 5 (최근 30일)
연승 김
연승 김 2021년 9월 29일
댓글: 연승 김 2021년 9월 30일
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
KSSV
KSSV 2021년 9월 29일
Already you have done it....what else you want?
연승 김
연승 김 2021년 9월 30일
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 ;

댓글을 달려면 로그인하십시오.

채택된 답변

DGM
DGM 2021년 9월 30일
편집: DGM 2021년 9월 30일
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
Walter Roberson
Walter Roberson 2021년 9월 30일
DGM's use of has() is better than what I came up with.
연승 김
연승 김 2021년 9월 30일
Thank you for your kind!!
C = cell2sym(children(fparent))
This code works well^^

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2021년 9월 30일
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

카테고리

Help CenterFile Exchange에서 Conversion Between Symbolic and Numeric에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by