0% found this document useful (0 votes)
2 views2 pages

Matrices in Python

The document contains three programs demonstrating basic matrix operations: addition, transpose, and multiplication. Each program initializes matrices, performs the respective operation, and prints the resulting matrix. The examples illustrate how to iterate through matrix elements to compute the results.

Uploaded by

ponjit.borgohain
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Matrices in Python

The document contains three programs demonstrating basic matrix operations: addition, transpose, and multiplication. Each program initializes matrices, performs the respective operation, and prints the resulting matrix. The examples illustrate how to iterate through matrix elements to compute the results.

Uploaded by

ponjit.borgohain
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Matrix Addition

# Program for Matrix Addition


X = [[1, 2, 3],
[4, 5, 6]]

Y = [[7, 8, 9],
[1, 1, 1]]

# Result matrix initialized with zeros


result = [[0, 0, 0],
[0, 0, 0]]

# Iterate through rows


for i in range(len(X)):
# Iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

print("Matrix Addition:")
for r in result:
print(r)

2. Matrix Transpose

# Program for Matrix Transpose


X = [[1, 2],
[3, 4],
[5, 6]]

# Result will have flipped dimensions (2x3 instead of 3x2)


result = [[0, 0, 0],
[0, 0, 0]]

for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]

print("Transposed Matrix:")
for r in result:
print(r)

3. Matrix Multiplication (Dot Product)

# Program for Matrix Multiplication


# 3x3 matrix
A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]

# 3x4 matrix
B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]

# Result will be 3x4


result = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]

# Iterate through rows of A


for i in range(len(A)):
# Iterate through columns of B
for j in range(len(B[0])):
# Iterate through rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]

print("Matrix Multiplication:")
for r in result:
print(r)

You might also like