On 09/09/2012 02:31 AM, akhil wrote:
> Hello,
> 
> 
> Given a set of m linear equations in n unknowns, how do I use SAGE to
> give me the coefficient matrix*A*(size m *n) and column vector *b*(size
> m*1) such that Ax = b; where *x*(size n*1) is the vector of unknowns ?

It depends on how those equations are given. You can get the `b` vector
easy enough. Let's declare some symbols:

  sage: x1,x2 = var('x1,x2')
  sage: a1,a2,a3,a4 = var('a1,a2,a3,a4')
  sage: b1,b2 = var('b1,b2')

Now, define one equation:

  sage: eqn1 = a1*x1 + a2*x2 == b1

We can use the `rhs` method to get the right-hand-side of an equation:

  sage: eqn1.rhs()
  b1

If we define another equation,

  sage: eqn2 = a3*x1 + a4*x2 == b2

And put both of them in a list,

  sage: eqns = [eqn1,eqn2]

We can write,

  sage: b = [eqn.rhs() for eqn in eqns]

Now, `b` is the vector you seek. I don't think there's a general way to
get `A` or `x` unless you input one of them yourself. Sage doesn't know
that we're solving for the x1,x2 -- we could just as well be solving for
a1,a2,a3,a4!

If you're using constants and not symbols, though, it's possible. Here's
an equation with fixed a1,a2, and b1:

  sage: eqn3 = 2*x1 + 3*x2 == 5

We can use the `variables` method to get the `x` vector:

  sage: x = eqn3.variables()
  sage: x
  (x1, x2)

If we define another equation with fixed coefficients,

  eqn4 = 4*x1 + 5*x2 == 6

We can then pick out the constants and stick them in a matrix `A`,

  sage: eqns = [eqn3,eqn4]
  sage: A = matrix(QQ,
             [[row.lhs().coefficient(xi) for xi in x] for row in eqns])

Now,

  sage: A
  [2 3]
  [4 5]

  sage: x
  (x1, x2)

  sage: b
  [b1, b2]

as desired.

-- 
You received this message because you are subscribed to the Google Groups 
"sage-support" group.
To post to this group, send email to sage-support@googlegroups.com.
To unsubscribe from this group, send email to 
sage-support+unsubscr...@googlegroups.com.
Visit this group at http://groups.google.com/group/sage-support?hl=en.


Reply via email to