I'm making a function to calculate a dot product when given two vectors. The code is later used in a matrix multiplication function. The issue I'm having is that the parameters passed in from the matrix multiplication function are 1x3 matrices that in order to multiply together, I need to use dot =A[0,,i]*B[0,i]. The submission website expects dot =A[i],B[i] and I'm not sure how to get my matrices converted to arrays. Picture of my two functions
I tried recreating the matrices and isolating rows but I still had [[1,2,3]] come up and mes with my dot product function.
CodePudding user response:
I suggest you to use the numpy library to perform matrix multiplication.
You can use the numpy.matmul
function to perform matrix multiplication. Read more about it here: https://numpy.org/doc/stable/reference/generated/numpy.matmul.html
You can also use the numpy.dot function to perform dot product. Read more about it here: https://numpy.org/doc/stable/reference/generated/numpy.dot.html
Here is an example of how to use the numpy library to perform matrix multiplication:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = np.matmul(a, b)
CodePudding user response:
In order to convert a 1x3 matrix into a one-dimensional array in Python, you can use the numpy
library. Here's one way you can do it:
import numpy as np
# Define the matrix
matrix = np.array([[1, 2, 3]])
# Convert the matrix to a one-dimensional array
array = matrix.ravel()
print(array)
The ravel()
method returns a one-dimensional array containing all the elements of the input array. This will give you the output [1 2 3]
.
Another way to achieve this is using np.squeeze()
method, this method can remove the single-dimensional entries, this way it will convert the matrix to array, like this:
import numpy as np
# Define the matrix
matrix = np.array([[1, 2, 3]])
# Convert the matrix to a one-dimensional array
array = np.squeeze(matrix)
print(array)
You can also use the numpy method flatten()
to get the same result.
import numpy as np
# Define the matrix
matrix = np.array([[1, 2, 3]])
# Convert the matrix to a one-dimensional array
array = matrix.flatten()
print(array)
Once you have the one-dimensional array, you can use the array indexing to access the elements of the array, like this:
dot =array[i]*B[i]
CodePudding user response:
Glancing at your image, I noticed the use of np.matrix
. Be careful with that. That's an array subclass designed years ago to make numpy
more friendly to wayward MATLAB users. It's use is discouraged now.
A key difference is that it must always be 2d:
In [108]: M = np.matrix([1,2,3])
In [109]: M
Out[109]: matrix([[1, 2, 3]]) # note the added dimension
In [110]: M.shape
Out[110]: (1, 3)
And ravel
doesn't remove that leading dimension:
In [111]: M.ravel()
Out[111]: matrix([[1, 2, 3]])
np.matrix
does have a A1
property, which ravels and converts to ndarray
, or rather converts to array and ravels:
In [112]: M.A1
Out[112]: array([1, 2, 3])
np.matrix
does matrix multiplication with using *
, though now @
is recommended operator that works with ndarray
as well
In [113]: M*M
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[113], line 1
----> 1 M*M
File ~\miniconda3\lib\site-packages\numpy\matrixlib\defmatrix.py:218, in matrix.__mul__(self, other)
215 def __mul__(self, other):
216 if isinstance(other, (N.ndarray, list, tuple)) :
217 # This promotes 1-D vectors to row vectors
--> 218 return N.dot(self, asmatrix(other))
219 if isscalar(other) or not hasattr(other, '__rmul__') :
220 return N.dot(self, other)
File <__array_function__ internals>:180, in dot(*args, **kwargs)
ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
With a (1,3) shape, we have to use a transpose to do dot
, producing (3,3) one way:
In [114]: M.T*M
Out[114]:
matrix([[1, 2, 3],
[2, 4, 6],
[3, 6, 9]])
or (1,1) the other:
In [115]: M*M.T
Out[115]: matrix([[14]])
where as using the 1d A1
gives a scalar, dot product:
In [116]: M.A1 @ M.A1
Out[116]: 14
While you are welcome to implement your own dot
(for learning purpose, I assume), be aware that numpy
has good code to do this for you.
np.dot
np.matmul
np.einsum