JACOBIAN
Overview
The JACOBIAN function computes the Jacobian matrix of a vector-valued function using CasADi’s symbolic differentiation capabilities (see CasADi documentation ). Given a function with components and variables , the Jacobian matrix collects all partial derivatives:
This example function is provided as-is without any representation of accuracy.
Usage
To use the function in Excel:
=JACOBIAN(expressions, var_values)expressions(string or 2D list of strings, required): One or more mathematical expressions defining the function components. Can be a single expression (e.g.,"x**2 * y") or a 2D list of expressions for vector-valued functions.var_values(2D list, required): A 2D list with two rows: the first row contains variable names as strings, and the second row contains their numeric values.
The function returns a 2D list representing the Jacobian matrix, where each row corresponds to the partial derivatives of one expression with respect to all variables, evaluated at the given point. If an error occurs during calculation, the function returns an error message string.
Examples
Example 1: Single Polynomial Expression
=JACOBIAN("x**2 * y", {{"x","y"},{2.0,3.0}})| d/dx | d/dy |
|---|---|
| 12.0 | 4.0 |
Example 2: Trigonometric and Polynomial Mix
=JACOBIAN("sin(x) + y**3", {{"x","y"},{1.0,2.0}})| d/dx | d/dy |
|---|---|
| 0.540 | 12.0 |
Example 3: Multiple Expressions at Same Point
=JACOBIAN({{"x**2 * y"}, {"sin(x) + y**3"}}, {{"x","y"},{2.0,3.0}})| d/dx | d/dy |
|---|---|
| 12.0 | 4.0 |
| -0.416 | 27.0 |
Example 4: Multiple Expressions at Different Point
=JACOBIAN({{"x**2 * y"}, {"sin(x) + y**3"}}, {{"x","y"},{1.5,1.0}})| d/dx | d/dy |
|---|---|
| 3.0 | 2.25 |
| 0.071 | 3.0 |
Example 2: Trigonometric and Polynomial Mix
Inputs:
| expressions | var_values | |
|---|---|---|
| sin(x) + y**3 | x | y |
| 1.0 | 2.0 |
Excel formula:
=JACOBIAN("SIN(x) + y^3", {"x","y";1,2})Expected output:
| d/dx | d/dy |
|---|---|
| 0.540 | 12.000 |
Example 3: Two Expressions Same Point
Inputs:
| expressions | var_values | ||
|---|---|---|---|
| x**2 * y | x | y | |
| sin(x) + y**3 | 2.0 | 3.0 |
Excel formula:
=JACOBIAN({"x^2 * y";"SIN(x) + y^3"}, {"x","y";2,3})Expected output:
| d/dx | d/dy |
|---|---|
| 12.000 | 4.000 |
| -0.416 | 27.000 |
Example 4: Two Expressions Different Point
Inputs:
| expressions | var_values | ||
|---|---|---|---|
| x**2 * y | x | y | |
| sin(x) + y**3 | 1.5 | 1.0 |
Excel formula:
=JACOBIAN({"x^2 * y";"SIN(x) + y^3"}, {"x","y";1.5,1})Expected output:
| d/dx | d/dy |
|---|---|
| 3.000 | 2.250 |
| 0.071 | 3.000 |
Python Code
import casadi as ca
# Note: scipy.differentiate module is not available in either Excel PY or Pyodide
def jacobian(expressions, var_values):
"""Calculate the Jacobian matrix of mathematical expressions with respect to specified variables.
Computes the Jacobian matrix using CasADi for symbolic differentiation, which allows efficient
and accurate computation of first-order partial derivatives. See [CasADi documentation](https://web.casadi.org/).
Args:
expressions (str or list[list[str]]): A single expression as a string, or a 2D list of
expressions for vector-valued functions. Example: "x**2 * y" or [["x**2 * y"], ["sin(x) + y**3"]].
var_values (list[list]): A 2D list with two rows: first row contains variable names as strings,
second row contains their numeric values. Example: [["x", "y"], [2.0, 3.0]].
Returns:
list[list[float]]: The Jacobian matrix as a 2D list of floats.
str: Error message if calculation fails.
This example function is provided as-is without any representation of accuracy.
"""
if isinstance(expressions, str):
expr_list = [expressions]
elif isinstance(expressions, list):
expr_list = [item for sublist in expressions for item in sublist if isinstance(item, str)]
else:
return "expressions must be a string or a 2D list of strings."
if not expr_list:
return "Expression list is empty or contains non-string elements."
if not isinstance(var_values, list) or len(var_values) != 2:
return "var_values should be a list of two lists: [[variable_names], [values]]"
var_names = var_values[0]
var_point_values = var_values[1]
if not isinstance(var_names, list) or not isinstance(var_point_values, list):
return "var_values must be [[variable_names], [values]]."
if len(var_names) == 0:
return "At least one variable name is required."
if len(var_names) != len(var_point_values):
return "Mismatch between number of variable names and number of values."
if not all(isinstance(name, str) and name.strip() for name in var_names):
return "Variable names must be non-empty strings."
try:
var_vals = [float(v) for v in var_point_values]
except (TypeError, ValueError):
return "Variable values must be numeric."
sym_vars = [ca.SX.sym(name) for name in var_names]
casadi_exprs = []
evaluation_context = {name: sym_vars[idx] for idx, name in enumerate(var_names)}
evaluation_context["ca"] = ca
evaluation_context["sin"] = ca.sin
evaluation_context["cos"] = ca.cos
evaluation_context["tan"] = ca.tan
evaluation_context["exp"] = ca.exp
evaluation_context["log"] = ca.log
evaluation_context["sqrt"] = ca.sqrt
evaluation_context["atan"] = ca.atan
evaluation_context["asin"] = ca.asin
evaluation_context["acos"] = ca.acos
evaluation_context["sinh"] = ca.sinh
evaluation_context["cosh"] = ca.cosh
evaluation_context["tanh"] = ca.tanh
evaluation_context["fabs"] = ca.fabs
evaluation_context["floor"] = ca.floor
evaluation_context["ceil"] = ca.ceil
for expr in expr_list:
try:
expr_obj = eval(expr, evaluation_context)
casadi_exprs.append(expr_obj)
except Exception as e:
return f"Invalid expression: {e}"
if not casadi_exprs:
return "Failed to parse any expressions."
casadi_expr_vector = ca.vertcat(*casadi_exprs)
J = ca.jacobian(casadi_expr_vector, ca.vertcat(*sym_vars))
jacobian_func = ca.Function('jacobian_func', sym_vars, [J])
result = jacobian_func(*var_vals)
if isinstance(result, ca.DM):
return result.full().tolist()
else:
return "Error during CasADi calculation: Unexpected result type."