I have the following Matlab code:
A=[length(x) sum(x) sum(y) sum(x.*y);
sum(x) sum(x.^2) sum(x.*y) sum(y.*x.^2);
sum(y) sum(x.*y) sum(y.^2) sum(x.*y.^2);
sum(x.*y) sum((x.^2).*y) sum(x.*y.^2) sum((x.^2).*(y.^2))];
v=[sum(z); sum(z.*x); sum(z.*y); sum(x.*y.*z)];
solution=inv(A)*v;
a=solution(1);
b=solution(2);
c=solution(3);
d=solution(4);
which I want to convert into Python. I have no knowledge of Matlab, and with some research came up with the following Python code:
A = [
[len(x), x.sum(), y.sum(), (x * y).sum()],
[x.sum(), (x**2).sum(), (x * y).sum(), ((y * x) ** 2).sum()],
[y.sum(), (x * y).sum(), (y**2).sum(), ((x * y) ** 2).sum()],
[(x * y).sum(), ((x**2) * y).sum(), ((x * y)**2).sum(), ((x**2) * (y**2)).sum()]
]
v = [z.sum(), (z * x).sum(), (z * y).sum(), (x * y * z).sum()]
solution = np.linalg.inv(A) * v
I excpected a list with 4 values, which should be the coefficients which I want to use for a function. However, the result is another matrix. What am I doing wrong?
CodePudding user response:
In the last step, you should use matrix multiplication instead of corresponding position multiplication.
Matrix multiplication uses operator@
:
solution = np.linalg.inv(A) @ v
Or function numpy.matmul
:
solution = np.matmul(np.linalg.inv(A), v)