简体   繁体   中英

About matrix vector operations in Python

I have a matrix of size nxm and a vector of size nx1. For example:

import numpy as np
matrix = np.array([[1, 2, 3],[4,5,6]])
vector = np.array([[10],[20]])

I want to obtain result = [[1+10, 2+10, 3+10],[4+20,5+20,6+20]] = [[11, 12, 13],[24,25,26]]

I am a little bit confused about matrix operations in python. I couldn't find the correct one to do that.

I believe you can just add themnumpy.add

import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
vector = np.array([[10], [20]])

print(vector + matrix)

Output:

[[11 12 13]
 [24 25 26]]

This will give you the output when added.

matrix = [[1, 2, 3],[4,5,6]]
vector = [10,20]
result = []
x = 0
for elem in matrix:
    for nums in elem:
        result.append(nums+vector[x])
    x += 1
print(result)

Output

[11, 12, 13, 24, 25, 26]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM