How can Tensorflow be used to add two matrices using Python?

TensorFlow is a machine learning framework provided by Google. It is an open-source framework used with Python to implement algorithms, deep learning applications, and mathematical operations. TensorFlow uses NumPy and multi-dimensional arrays called tensors to perform complex computations efficiently.

The framework supports deep neural networks, is highly scalable, and comes with GPU computation capabilities. It includes many machine learning libraries and popular datasets, making it ideal for both research and production environments.

Installation

Install TensorFlow using pip ?

pip install tensorflow

Understanding Tensors

A tensor is TensorFlow's primary data structure - essentially a multi-dimensional array. Tensors have three key attributes:

  • Rank: The number of dimensions (0D scalar, 1D vector, 2D matrix, etc.)
  • Type: The data type of elements (int32, float32, etc.)
  • Shape: The size of each dimension (rows × columns for 2D)

Adding Two Matrices

Here's how to add two matrices using TensorFlow's tf.add() function ?

import tensorflow as tf
import numpy as np

# Create two matrices using NumPy
matrix_1 = np.array([(1,2,3),(3,2,1),(1,1,1)], dtype='int32')
matrix_2 = np.array([(0,0,0),(-1,0,1),(3,3,4)], dtype='int32')

print("The first matrix is:")
print(matrix_1)
print("The second matrix is:")
print(matrix_2)

# Convert NumPy arrays to TensorFlow constants
matrix_1 = tf.constant(matrix_1)
matrix_2 = tf.constant(matrix_2)

# Add the matrices
matrix_sum = tf.add(matrix_1, matrix_2)
print("The sum is:")
print(matrix_sum)
The first matrix is:
[[1 2 3]
 [3 2 1]
 [1 1 1]]
The second matrix is:
[[ 0  0  0]
 [-1  0  1]
 [ 3  3  4]]
The sum is:
tf.Tensor(
[[1 2 3]
 [2 2 2]
 [4 4 5]], shape=(3, 3), dtype=int32)

Alternative Method

You can also use the + operator directly with TensorFlow tensors ?

import tensorflow as tf

# Create matrices directly as TensorFlow constants
matrix_1 = tf.constant([[1, 2, 3], [3, 2, 1], [1, 1, 1]])
matrix_2 = tf.constant([[0, 0, 0], [-1, 0, 1], [3, 3, 4]])

# Add using + operator
matrix_sum = matrix_1 + matrix_2
print("Matrix sum using + operator:")
print(matrix_sum)
Matrix sum using + operator:
tf.Tensor(
[[1 2 3]
 [2 2 2]
 [4 4 5]], shape=(3, 3), dtype=int32)

How It Works

  • NumPy arrays are converted to TensorFlow constants using tf.constant()
  • tf.add() performs element-wise addition of the two matrices
  • The result is a new tensor with the same shape and compatible data type
  • Both matrices must have the same dimensions for addition to work

Conclusion

TensorFlow provides simple matrix addition through tf.add() or the + operator. Convert NumPy arrays to TensorFlow constants first, then perform element-wise addition to get the resulting tensor.

Updated on: 2026-03-25T15:31:34+05:30

687 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements