#๐Ÿ”’ Is there a way to make this code work without a nested for loop

16 messages ยท Page 1 of 1 (latest)

cobalt kernel
#
def generate_matrix(equation, variables):
    matrix_size = len(variables)
    matrix = sp.zeros(matrix_size, matrix_size)
    for i in range(matrix_size):
        for j in range(matrix_size):
            matrix[i, j] = sp.diff(equation, variables[i], variables[j])
    return matrix
eternal fractalBOT
#

@cobalt kernel

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

vagrant elk
#

Is sp for sympy?

#

Are you looking for the "Hessian matrix"?

cobalt kernel
#

sp is for sympy

#

yeah it would be the hessian matrix

#

but it's really for computing the mass, stiffness and damping matrix.

vagrant elk
#

You could also rewrite it as a comprehension you fed to sp.Matrix() but it's still got the word for in it twice then so it maybe doesn't improve on what you had.

#

something like

def generate_matrix(equation, variables):
    matrix_size = len(variables)
    matrix = sp.Matrix([[sp.diff(equation, variables[i], variables[j]) 
                         for j in range(matrix_size)] 
                        for i in range(matrix_size)])
    return matrix
``` but yeah I don't really like that better
#

sp.hessian() seems pretty slick

cobalt kernel
#

I think their implementation is similar because they takea around the same time, I'd have to add some timing to really get a accurate reading

vagrant elk
#

py-spy is my favorite profiler at the moment, lemme know if you find something cooler

eternal fractalBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.