1

I am trying to multiply columns of a numpy matrix together. I have followed the code given in this question.

Here is what the column looks like:

enter image description here

Here is what happens when I try to multiply two columns of the matrix together.

enter image description here

Maybe the issue is that the column is stored differently? Some of the printouts in the other questions do not have the numbers stored in separate lists.

Community
  • 1
  • 1
goldisfine
  • 4,302
  • 10
  • 49
  • 77

3 Answers3

3

With np.matrix, the * operator does matrix multiplication rather than element-wise multiplication, which is what I assume you're trying to do.

You get a ValueError because the two column vectors are not properly aligned for matrix multiplication. Their inner dimensions don't match, since their shapes are (N, 1) and (N, 1) respectively. They would need to be either (1, N), (N, 1) (for the inner product) or (N, 1), (1, N) (for the outer product) in order for matrix multiplication to work.

If you choose to stick to using np.matrix to hold your data, you could use the np.multiply() function to do element-wise multiplication:

result = np.multiply(new_train_data[:, 0], new_train_data[:, 1])

However, I would recommend that you use np.array instead of np.matrix in future. With np.array the * operator does element-wise multiplication, and the np.dot() function (or the .dot() method of the array) does matrix multiplication.

ali_m
  • 62,795
  • 16
  • 193
  • 270
1

new_train_data is evidently a matrix (subclass of ndarray). Its * is defined as matrix multiplication (like the np.dot), not the element by element multiplication of regular numpy arrays. Hence the 'alignment' error message.

hpaulj
  • 175,871
  • 13
  • 170
  • 282
-2

Well in the answer it uses numpy.dot to multiply n*n with n...works for me!