# How to create a constrained symbolic vector

I am trying to emulate the following Mathematica code that returns the desired result. https://www.dropbox.com/s/awk0dj5po9k... The part I can't figure is how to constrain a symbolic vector to 1 and still retain it's vector form Here's what I have so far, but it doesn't work:

p1,p2,p3=var('p1,p2,p3')
A1=matrix(QQ,[[1,-1],[-1,1]])
sum1=p1+p2
sum1=1
P1=matrix(SR,[p1,p2])
result1=P1*A1*P1.transpose()
result1.simplify_full()

edit retag close merge delete

I tried to understand what you wanted to do!, but it's probably not what I wrote below, you should give more precision. Tell us what's wrong with my (probably unfortunate) attempt below to figure out what you wanted.

you have a button 101 010 (header when you write message) to tag the code part, use it.

var('p10,p11',domain="real")
var('p20,p21',domain="real")
P1=vector([p10,p11])
P2=vector([p20,p21])
A1=matrix(QQ,[[1,-1],[-1,1]])
sum1=P1+P2
assume(sum1.norm()==1)
P1=matrix(SR,[P1,P2])
result1=P1*A1*P1.transpose()
result1.simplify_full()

( 2022-03-19 19:16:54 +0100 )edit

OOps ! The first time I click on your link I did not see the mathematica code . disregard my comment above. Sorry.

( 2022-03-19 19:25:53 +0100 )edit

I must add that upon review, my code is doing what is expected, but the addition of your line of code to normalize is extremely helpful. thank you.

( 2022-03-19 20:24:43 +0100 )edit

Sort by ยป oldest newest most voted

A few solutions (there may well be others, which I'm too (lazy|dumb) to think of) :

p1, p2 = var("p1, p2")
A1 = matrix(QQ, [[1, -1], [-1, 1]])
# Use a vector rather than a 2x1 matrix (cleaner...)
P1 = vector(SR, [p1, p2])
# Using a constraint
with assuming(P1.norm()==1): res = (P2*A1*P2).simplify_full()
# Better ?
with assuming(P1.norm()==1): resf = (P2*A1*P2).factor()
# One can also "brute force" an explicit substitution
# First solution : substitute before computing
P2 = vector(map(lambda u:u.subs(solve(p1 + p2 == 1, p2)[0]), P1))
res1 = (P2*A1*P2).simplify_full()
res1f = res1.factor()
# Second solution : substitute after computing
res2 = (P1*A1*P1).subs((p1 + p2==1).solve(p2)[0]).simplify_full()
res2f = res2.factor()


Checks :

sage: res, resf, res1, res1f, res2, res2f
(4*p1^2 - 4*p1 + 1,
(2*p1 - 1)^2,
4*p1^2 - 4*p1 + 1,
(2*p1 - 1)^2,
4*p1^2 - 4*p1 + 1,
(2*p1 - 1)^2)


HTH,

more