Ask Your Question

derivative of multivariate equation with nested sum

asked 2013-12-30 13:36:27 +0200

ibayer gravatar image

updated 2013-12-30 13:39:31 +0200


I often have to deal with functions like the one below, take derivatives and so on. I would really like to know if I could use a CAS like SAGE to do this tedious and error prone calculations but I couldn't find a similar kind of function in the docs and tutorials.

My questions are:

  • how can I write this function in SAGE ?

for $x\in \mathbf{R}^p; v \in \mathbf{R}^{p \times k}$
$$y(x, v) := \sum^p_{i=1} \sum^p_{j>i} \sum_{f=1}^k v_{i,f} v_{j,f} x_i x_j = \sum^p_{i=1} \sum^p_{j>i} \langle v_{:,i}, v_{;,j} \rangle x_i x_j$$

  • calculate the partial derivatives $\frac{\partial y(x,v)}{\partial v_{i,j}}$ ?
  • or the the derivative with respect to the column-vector $\frac{\partial y(x,v)}{\partial v_{:, i} }$ ?

Or is there a better way to work with this kind of function in SAGE? (the function above is only an example)


edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2014-01-02 09:09:23 +0200

ppurka gravatar image

updated 2014-01-02 09:10:59 +0200

If your p and k are variables, then I don't know any way of doing it. But if they are fixed, then you can create them like this

sage: V = [var(['v_'+str(i)+'_'+str(j) for j in xrange(4)]) for i in xrange(5)] 
sage: V
[(v_0_0, v_0_1, v_0_2, v_0_3),
 (v_1_0, v_1_1, v_1_2, v_1_3),
 (v_2_0, v_2_1, v_2_2, v_2_3),
 (v_3_0, v_3_1, v_3_2, v_3_3),
 (v_4_0, v_4_1, v_4_2, v_4_3)]
sage: X = var(['x'+str(i) for i in xrange(5)])   
sage: X
(x0, x1, x2, x3, x4)

And now, your indices will match the variable names:

sage: V[0][1]
sage: V[2][3]

And you can do derivatives:

sage: f = sum(V[i][j] * X[i] * X[j] for i in xrange(3) for j in xrange(3))
sage: f
v_0_0*x0^2 + v_0_1*x0*x1 + v_1_0*x0*x1 + v_1_1*x1^2 + v_0_2*x0*x2 + v_2_0*x0*x2 + v_1_2*x1*x2 + v_2_1*x1*x2 + v_2_2*x2^2
sage: f.derivative(V[0][0])
edit flag offensive delete link more


Thanks for your answer this is a nice approach for an intermediate solution. p and k are indeed variables and I'm looking more for a solution like $\frac{\partial y(x,v)}{\partial v_{l,f}} = x_l \sum_{j\neq l} v_{j,f} x_j$ . Maybe this is a situation where its just simpler to do it by hand and and use finite difference to check if the gradient is correct...

ibayer gravatar imageibayer ( 2014-01-11 14:31:13 +0200 )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


Asked: 2013-12-30 13:36:27 +0200

Seen: 613 times

Last updated: Jan 02 '14