How do you Add to a Matrix in Python?

A matrix can only be added to or subtracted from another matrix if the two matrices have the same dimensions.

Suppose we have two matrices E and D.

Example 1:

E = [[1,2],[3,4]]

DY = [[4,5],[6,7]]

then we get

E+D = [[5,7],[9,11]]

Example 2:

E = [[1,2],[3,4],[8,3]]

D = [[4,5],[6,7],[4,7]]

then we get

E+D = [[5,7],[9,11],[12,10]]

Look at the example given below to understand how to add the elements in Python:

Source Code:

                    
import numpy as np

Â Â # The first matrix will be

P = np.array([[1, 2], [3, 4]])

#The second matrix will be

Q = np.array([[4, 5], [6, 7]])

print("Elements of the first matrix")

print(P)

print("Elements of the second matrix")

print(Q)

Â Â # adding two matrix

print("The sum of the two matrices is")

Output:

Elements of the first matrix

[[1 2]

Â [3 4]]

Elements of the second matrix

[[4 5]

Â [6 7]]

The sum of the two matrices is

[[ 5 7]

Â [ 9 11]]



Related Questions

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
Ashhar Firdausi
IIT Roorkee
Biology
Dr. Nazma Shaik
VTU
Chemistry
Gaurav Tiwari
APJAKTU
Physics
Get Started