First time here? Check out the FAQ!

Ask Your Question
0

How to split a function into separate components (according to their variables)?

asked 0 years ago

Afandi_MohAlsh gravatar image

updated 0 years ago

Hello there,

I had come across this question on the MATLAB Help Center website and was wondering if there was an equivalent answer in Sage......

if I defined an equation/function as below

x1, x2, y1, y2 = var("x1, x2, y1, y2")

f = 10*x1 + 20*x2 + 10*y1 + 10*y2

how can I split it as below ? :

f_x1 = 10*x1 ;
f_x2 = 20*x2 ; 
f_y1 = 10*y1 ; 
f_y2 = 20*y2 ;

I'd appreciate any suggestions.....

--Moh

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
2

answered 0 years ago

FrédéricC gravatar image

like this

sage: f.operands()
Preview: (hide)
link

Comments

1

Is there a way to find, for example, f_x1=10*x1+5*x1^2 for the following f?

f = 10*x1 + 20*x2 + 10*y1 + 10*y2 + 5*x1^2 - 7*x2^6
tolga gravatar imagetolga ( 0 years ago )

Thank you........ I thought the operand() method identified only factors rather than general elements of an expression. I would also like to see if there's an answer to tolga's question too.....

Afandi_MohAlsh gravatar imageAfandi_MohAlsh ( 0 years ago )

The following is a way to get the parts for a given variable:

def dependentpart(f, val):
    terms = f.operands()
    mypart = sum(item for item in terms if item.has(val))
    return mypart

x1, x2, y1, y2 = var("x1, x2, y1, y2")

f = 10*x1 + 20*x2 + 10*y1 + 10*y2 + 5*x1^2 - 7*x2^6

f_x1=dependentpart(f,x1)
f_x2=dependentpart(f,x2)
f_y1=dependentpart(f,y1)
f_y2=dependentpart(f,y2)

show(f_x1)
show(f_x2)
show(f_y1)
show(f_y2)
tolga gravatar imagetolga ( 0 years ago )

Also, check the following:

def dependentpart(f, val):
    terms = f.operands()
    mypart = sum(item for item in terms if item.has(val))
    return mypart

x1, x2, y1, y2 = var("x1, x2, y1, y2")

f = 10*x1 + 20*x2 + 10*y1 + 10*y2 + 5*x1^2 - 7*x2^6

myvars = f.variables()
forallvars=[dependentpart(f, val) for val in myvars]
show(forallvars)
tolga gravatar imagetolga ( 0 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 0 years ago

Seen: 171 times

Last updated: Nov 22 '24