In Python, I have a column array and a row array, say, [1, 3, 5] and [2, 4, 6, 8]' and I want to create a matrix of size 4*3 by multiplying each element in both of them. Is it possible to do without looping?
            Asked
            
        
        
            Active
            
        
            Viewed 1,120 times
        
    0
            
            
        - 
                    2Please give an example of the output. – sophros Nov 06 '18 at 18:21
- 
                    1You can use `numpy` for this. First `import numpy as np` and then I think you're looking for: `np.array([1, 3, 5])*np.array([[2], [4], [6], [8]])` – pault Nov 06 '18 at 18:24
- 
                    1Possible duplicate of [numpy matrix vector multiplication](https://stackoverflow.com/questions/21562986/numpy-matrix-vector-multiplication) – pault Nov 06 '18 at 18:26
2 Answers
1
            
            
        Vectorized calculation are best done with numpy:
import numpy as np
x = np.arange(1,6,2) # [1,3,5]
y = np.arange(2,9,2) # [2,4,6,8]
x = np.array([x]) # add dimension for transposing.
y = np.array([y])
result = np.dot(x.T, y)
result:
array([[ 2,  4,  6,  8],
       [ 6, 12, 18, 24],
       [10, 20, 30, 40]])
 
    
    
        Rocky Li
        
- 5,641
- 2
- 17
- 33
0
            
            
        You can use the below code
import numpy as np
>>> x1 = np.arange(2,9,2)   # [2,4,6,8]
>>> x2 = np.arange(1,6,2)   # [1,3,5]
>>> result = x1.dot(x2)
>>> print result
 
    
    
        Prasan Karunarathna
        
- 377
- 2
- 7
- 
                    `ValueError: shapes (4,) and (3,) not aligned: 4 (dim 0) != 3 (dim 0)` – Rocky Li Nov 06 '18 at 18:52