Ask Your Question
0

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

asked 2024-11-22 10:40:30 +0100

Afandi_MohAlsh gravatar image

updated 2024-11-22 10:43:20 +0100

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

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
2

answered 2024-11-22 11:18:23 +0100

FrédéricC gravatar image

like this

sage: f.operands()
edit flag offensive delete link more

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 ( 2024-11-24 08:19:13 +0100 )edit

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 ( 2024-11-24 09:43:25 +0100 )edit

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 ( 2024-11-25 07:17:25 +0100 )edit

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 ( 2024-11-25 07:22:12 +0100 )edit

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: 2024-11-22 10:40:30 +0100

Seen: 104 times

Last updated: Nov 22