But function f is a problem because I don't know how to combine the mesh with the matrix, is there a smart way to solve this problem?
CodePudding user response:
It looks like your code for g
is very close to the one for f
. You could just define your M matrix and include it in the matrix multiplication. See code below for more details:
import numpy as np
import matplotlib.pyplot as plt
def f_function(diagonal_values):
fig = plt.figure(figsize=(15,8))
data = np.linspace(-4, 4, 20)
x_1, x_2 = np.meshgrid(data, data, indexing="ij")
fx = np.zeros_like(x_1)
#Defining M
M=np.diag(diagonal_values)
print(M)
for i in range(data.shape[0]):
for j in range(data.shape[0]):
x = np.array([x_1[i,j], x_2[i,j]])
f = x.T @ M @ x
fx[i,j] = f
ax = fig.add_subplot(121, projection="3d")
surf = ax.plot_surface(x_1, x_2, fx)
ax.set_xlabel("x_1")
ax.set_ylabel("x_2")
ax.set_zlabel("f")
#Randomly picking diagonal values
diag_values=np.random.uniform(0,10,2)
print('Diagonal values: ' str(diag_values))
f_function(np.array(diag_values))
The output gives:
Diagonal values: [8.62030848 2.68367524]
And the plot: