Skip to content
Advertisement

Multiply two matrices with different dimensions python

Error: ValueError: shapes (3,1) and (3,2) not aligned: 1 (dim 1) != 3 (dim 0)

The error occurs because the matrices are different sizes, but how can I multiply two matrices with different size and where the resulting output should be: [-0.78 0.85]?

import numpy as np

x1 = 3-7/3;
x2 = 2-4/3;
x3 = 1-5/3;

X = ([x1], [x2],[x3])

V = ([-0.99, -0.13], [-0.09, 0.70],[0.09, -0.70])

res = np.dot(X,V)
print("Res: ",res)

Any help is appreciated!


Mathematical question, for better understanding:

A principal component analysis is carried out on a dataset comprised of three data points x1, x2 and x3 collected in a N × M matrix X such that each row of the matrix is a data point. Suppose the matrix X ̃ corresponds to X with the mean of each columns substracted i.e.

X = ([3.00, 2.00, 1.00],[4.00, 1.00, 2.00],[0.00, 1.00, 2.00])

and suppose X ̃ has the singular value decomposition:

V = ([-0.99, -0.13, -0.00], [-0.09, 0.70, -0.71],[0.09, -0.70, -0.71])

What is the (rounded to two significant digits) coordinates of the first observation x1 projected onto the 2-Dimensional subspace containing the maximal variation?

Answer:

The projection can be found by substracting the mean from X and projecting onto the first two columns of V. The first point with the mean subtracted has coordinates: [2-7/3 2-4/3 1-5/3]

This should be (left) multiplied with the first two columns of V:

([3-7/3], [2-4/3],[1-5/3]) * ([-0.99, -0.13], [-0.09, 0.70],[0.09, -0.70]) = [-0.78 0.85]


So I am trying to find out how to calculate this in python.

Advertisement

Answer

I am assuming you wish to perform matrix multliplication. This cannot be achieved if the dimensions of the matrices are different. You can achieve the desired result by using reshape and numpy.matmul().
Code:

import numpy as np

x1 = 3-7/3;
x2 = 2-4/3;
x3 = 1-5/3;

X = np.array([[x1], [x2],[x3]])
X = X.reshape(1, 3)

V = np.array([[-0.99, -0.13], [-0.09, 0.70],[0.09, -0.70]])

res = np.matmul(X, V)
print("Res: ",res)
Advertisement