Home > Back-end >  1D Arrays elements
1D Arrays elements

Time:11-29

I was doing numpy basics and I was trying to do some matrix multiplication, my array A is 3 rows x 3 columns while my array x is 1 row x 3 columns (Or so I thought), I was expecting it to give an error since the number of columns of A needs to be same as the number of rows of x, but they are not as 3 is not 1, but it gave [24 15 29], no error given. So, I am confused whether 1d arrays have 1 row and n columns or vice versa.

import numpy as np

A = np.array([[4, 2, 1],[1, 3, 1],[2, 3, 6]])
x = np.array([4, 3, 2])

print(np.matmul(A, x))

CodePudding user response:

I think this post contains an answer to your question: https://numpy.org/doc/stable/reference/generated/numpy.matmul.html

Namely, with numpy.matmul, a second dimension is added automatically to the one-dimensional vector, so that the multiplication is possible. Quoting from the linked page:

If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed.

CodePudding user response:

If you do this, print(x.shape)) you will see the shape of your array is (3,). Meaning it’s a 1-dimensional array.

The syntax np.array([4, 3, 2]) is used for making a 1-dimensional array (n,). Not that there is only one square bracket in your code.

If you want it to be 1x3 (2-dimensional) you have to do this, np.array([[4,3,2]]).

Here you are making, (1,3) or 1 row, 3 columns.

[[4,3,2]]

Note that there is a square bracket within a square bracket. The outer square bracket is for the whole matrix. Each square bracket within it represents a row, and each comma separating it will represent another row.

You can also make a 3x1 (2-dimensional) matrix like this, np.array([[4],[3],[2]]). See how there is an outer square bracket, essentially you are making, (1,3) or 3 rows, 1 column.

[[4],
[3],
[2]]

In your example, matmul will accept either the correct dimensions or produce an error, since your 1-dimensional array had the right dimensions (3,), since m x n multiplied by n x p produces an m x p matrix, and n = n has to be true, it projected your array as a 2-dimensional matrix and did the calculation, if you had done (4,) or anything by (3,), it wouldn't have worked.

CodePudding user response:

You can also use the @ symbol for matrix multiplication. If you turn the array into a matrix, it may do what you expect

import numpy as np
A = np.array([[4, 2, 1],[1, 3, 1],[2, 3, 6]])
x = np.array([4, 3, 2])
print(A @ x) # 1D array of shape (3,)
print(A @ x[:, np.newaxis]) # 2D array of shape (3, 1)

B = np.matrix(A) # make into matrix
y = np.matrix(x) # make into matrix

#print(B @ y) # gives error, as now matrix multiplication cannot be done
print(B @ y.T) # 2D matrix with one column
  • Related