Multiply vector with matrix element wise [duplicate] - python

This question already has answers here:
Multiplying across in a numpy array
(7 answers)
Closed 3 years ago.
I have a (n,1) np-array, for example array([1 2 3]) that I would like to multiply element wise with a np-matrix (n,m), for example array([[1 1 1], [2 2 2], [3 3 3]]) so that I will get:
array([[1 1 1], [4 4 4], [9 9 9]])
How can I do that?
I have tried with np.multiply and np.dot.

Reshape your vector so that it contains 3 rows instead of 3 columns:
v = np.array([1, 2, 3])
m = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
u = v.reshape(*v.shape, 1)
u * m # results in [[1, 1, 1], [4, 4, 4], [9, 9, 9]]

Related

How to get the scalar multiplication between 2 matrices?

I'm new with Python and programming in general.
I want to create a function that multiplies two np.array of the same size and get their scalar value, for example:
matrix_1 = np.array([[1, 1], [0, 1], [1, 0]])
matrix_2 = np.array([[1, 2], [1, 1], [0, 0]])
I want to get 4 as output ((1 * 1) + (1 * 2) + (0 * 1) + (1 * 1) + (1 * 0) + (0 * 0))
Thanks!
Multiply two matrices element-wise
Sum all the elements
multiplied_matrix = np.multiply(matrix_1,matrix_2)
sum_of_elements = np.sum(multiplied_matrix)
print(sum_of_elements) # 4
Or in one shot:
print(np.sum(np.multiply(matrix_1, matrix_2))) # 4
You can make use of np.multiply() to multiply the two arrays elementwise, then we call np.sum() on this matrix. So we thus can calculate the result with:
np.multiply(matrix_1, matrix_2).sum()
For your given sample matrix, we thus obtain:
>>> matrix_1 = np.array([[1, 1], [0, 1], [1, 0]])
>>> matrix_2 = np.array([[1, 2], [1, 1], [0, 0]])
>>> np.multiply(matrix_1, matrix_2)
array([[1, 2],
[0, 1],
[0, 0]])
>>> np.multiply(matrix_1, matrix_2).sum()
4
There are a couple of ways to do it (Frobenius inner product) using numpy, e.g.
np.sum(A * B)
np.dot(A.flatten(), B.flatten())
np.trace(np.dot(A, B.T))
np.einsum('ij,ij', A, B)
One recommended way is using numpy.einsum, since it can be adapted to not only matrices but also multiway arrays (i.e., tensors).
Matrices of the same size
Take the matrices what you give as an example,
>>> import numpy as np
>>> matrix_1 = np.array([[1, 1], [0, 1], [1, 0]])
>>> matrix_2 = np.array([[1, 2], [1, 1], [0, 0]])
then, we have
>>> np.einsum('ij, ij ->', matrix_1, matrix_2)
4
Vectors of the same size
An example like this:
>>> vector_1 = np.array([1, 2, 3])
>>> vector_2 = np.array([2, 3, 4])
>>> np.einsum('i, i ->', vector_1, vector_2)
20
Tensors of the same size
Take three-way arrays (i.e., third-order tensors) as an example,
>>> tensor_1 = np.array([[[1, 2], [3, 4]], [[2, 3], [4, 5]], [[3, 4], [5, 6]]])
>>> print(tensor_1)
[[[1 2]
[3 4]]
[[2 3]
[4 5]]
[[3 4]
[5 6]]]
>>> tensor_2 = np.array([[[2, 3], [4, 5]], [[3, 4], [5, 6]], [[6, 7], [8, 9]]])
>>> print(tensor_2)
[[[2 3]
[4 5]]
[[3 4]
[5 6]]
[[6 7]
[8 9]]]
then, we have
>>> np.einsum('ijk, ijk ->', tensor_1, tensor_2)
248
For more usage about numpy.einsum, I recommend:
Understanding NumPy's einsum

reshaping 2-d array using specific block shape [duplicate]

This question already has answers here:
Flatten or group array in blocks of columns - NumPy / Python
(6 answers)
Closed 3 years ago.
I've got problem with reshaping simple 2-d array into another.
Let`s assume matrix :
[[4 1 2 1 2 4 1 2 4]
[2 3 0 3 0 2 3 0 2]
[5 5 1 5 1 5 5 1 5]
[6 6 6 6 6 6 6 6 6]]
What I want to do is to reshape it to (12, 3) matrix, but using (4, 3) block. What I meant to do is to get matrix like:
[[4 1 2
2 3 0
5 5 1
6 6 6
1 2 4
3 0 2
5 1 5
6 6 6
1 2 4
3 0 2
5 1 5
6 6 6]]
I have highlighted the "egde" of cutting this matrix by additional newline.
I`ve tried numpy reshape (with all available order parameter value), but still I get array with "mixed" values.
You can always do this manually for custom reshapes:
import numpy as np
data = [[4, 1, 2, 1, 2, 4, 1, 2, 4],
[2, 3, 0, 3, 0, 2, 3, 0, 2],
[5, 5, 1, 5, 1, 5, 5, 1, 5],
[6, 6, 6, 6, 6, 6, 6, 6, 6]]
X = np.array(data)
Z = np.r_[X[:, 0:3], X[:, 3:6], X[:, 6:9]]
print(Z)
yields
array([[4, 1, 2],
[2, 3, 0],
[5, 5, 1],
[6, 6, 6],
[1, 2, 4],
[3, 0, 2],
[5, 1, 5],
[6, 6, 6],
[1, 2, 4],
[3, 0, 2],
[5, 1, 5],
[6, 6, 6]])
note the special np.r_ operator that concatenates arrays on rows (first axis). It is just a handy alias for np.concatenate.

Swap two rows in a numpy array in python [duplicate]

This question already has an answer here:
Row exchange in Numpy [duplicate]
(1 answer)
Closed 4 years ago.
How to swap xth and yth rows of the 2-D NumPy array? x & y are inputs provided by the user.
Lets say x = 0 & y =2 , and the input array is as below:
a = [[4 3 1]
[5 7 0]
[9 9 3]
[8 2 4]]
Expected Output :
[[9 9 3]
[5 7 0]
[4 3 1]
[8 2 4]]
I tried multiple things, but did not get the expected result. this is what i tried:
a[x],a[y]= a[y],a[x]
output i got is:
[[9 9 3]
[5 7 0]
[9 9 3]
[8 2 4]]
Please suggest what is wrong in my solution.
Put the index as a whole:
a[[x, y]] = a[[y, x]]
With your example:
a = np.array([[4,3,1], [5,7,0], [9,9,3], [8,2,4]])
a
# array([[4, 3, 1],
# [5, 7, 0],
# [9, 9, 3],
# [8, 2, 4]])
a[[0, 2]] = a[[2, 0]]
a
# array([[9, 9, 3],
# [5, 7, 0],
# [4, 3, 1],
# [8, 2, 4]])

How can I create a vector from a matrix using specified colums from each row without looping in Python? [duplicate]

This question already has answers here:
using an numpy array as indices of the 2nd dim of another array? [duplicate]
(2 answers)
Closed 6 years ago.
Say I have a matrix of shape (N,d) and a vector of size N which says which column in the matrix is of relevance to a given row. How can I return the vector of size N which is given by the values in the matrix and the relevant column?
For example:
M = [[ 2, 4, 1, 8],
[3, 5, 7, 1],
[2, 5, 3, 9],
[1, 2, 3, 4]]
V = [2, 1, 0, 1]
I tried something like:
M[:,V]
but this returns a matrix which is NXN
Is there a simple way to format this which does not involve writing a for-loop so that I could get the following vector:
V' = [1,5,2,2]
Use np.arange(len(V)) for indexing the row numbers and V for columns:
In [110]: M = [[ 2, 4, 1, 8],
.....: [3, 5, 7, 1],
.....: [2, 5, 3, 9],
.....: [1, 2, 3, 4]]
In [111]: V = [2, 1, 0, 1]
In [112]:
In [112]: M = np.array(M)
In [113]: M[np.arange(len(V)),V]
Out[113]: array([1, 5, 2, 2])

Simplfy row AND column extraction, numpy [duplicate]

This question already has answers here:
Subsetting a 2D numpy array
(5 answers)
Closed 7 years ago.
I wish to extract rows and columns from a matrix using a single "fancy" slice, is this possible?
m = matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
My target is
matrix([[1, 3],
[7, 9]])
Where I have a list of the items I want
d = [0,2]
I can achieve the functionality by
m[d][:,d]
But is there a simpler expression?
You can do this using numpy.ix_:
m = matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
d = [0,2]
print m[ix_(d,d)]
which will emit:
[[1 3]
[7 9]]

Categories