calculate the gradient of the matrix with apply_map

asked 2020-12-03 04:37:20 +0200

karl gravatar image

I wrote this code to calculate the gradient of the matrix, but I got the wrong answer


W = matrix(SR, 2, var(','.join([f'w{i}' for i in range(4)]), domain=RR))

x = vector(SR, 2, var('x1,x2', domain=RR))

y = sum(W*x)

f(x) = y.diff(x)

W.apply_map(f)


output:

[0 0]

[0 0]


what I expect is

[x1 x2]

[x1 x2]

edit retag flag offensive close merge delete

Comments

Welcome to Ask Sage!

Thank you for your question!

slelievre gravatar imageslelievre ( 2020-12-03 16:44:41 +0200 )edit

To display blocks of code or error messages in Ask Sage, skip a line above and below, and do one of the following (all give the same result):

  • indent all code lines with 4 spaces
  • select all code lines and click the "code" button (the icon with '101 010')
  • select all code lines and hit ctrl-K

For instance, typing

If we define `f` by

    def f(x, y, z):
        return x * y * z

then `f(2, 3, 5)` returns `30` but `f(2*3*5)` gives:

    TypeError: f() takes exactly 3 arguments (1 given)

produces:

If we define f by

def f(x, y, z):
    return x * y * z

then f(2, 3, 5) returns 30 but f(2*3*5) gives:

TypeError: f() takes exactly 3 arguments (1 given)

Please edit your question to do that.

slelievre gravatar imageslelievre ( 2020-12-03 16:44:47 +0200 )edit

I don't understand what you want to achieve with your code. Are you looking for the gradient of y as a function of x?
In any case, does this question help?

Florentin Jaffredo gravatar imageFlorentin Jaffredo ( 2020-12-04 13:43:38 +0200 )edit