Accessing Elements of Tensor

We can access the elements in the tensor vector using the index of elements.

Syntax:

tensor_name([index])

Where the index is the position of the element in the tensor:

  • Indexing starts from 0 from first
  • Indexing starts from -1 from last

Example: Python program to access elements using the index.

Python3




# importing torch module
import torch
  
# create one dimensional tensor with integer type elements
a = torch.tensor([10, 20, 30, 40, 50])
  
# get 0 and 1 index elements
print(a[0], a[1])
  
# get 4 th index  element
print(a[4])
  
# get 4 index element from last
print(a[-4])
  
# get 2 index element from last
print(a[-2])


Output:

tensor(10) tensor(20)
tensor(50)
tensor(20)
tensor(40)

We can access n elements at a time using the”:” operator, This is known as slicing.

Syntax:

tensor([start_index:end_index])

Where start_index is the starting index and end_index is the ending index.

Example: Python program to access multiple elements.

Python3




# importing torch module
import torch
  
# create one dimensional tensor with integer type elements
a = torch.tensor([10, 20, 30, 40, 50])
  
# access elements from 1 to 4
print(a[1:4])
  
# access from 4
print(a[4:])
  
# access from last
print(a[-1:])


Output:

tensor([20, 30, 40])
tensor([50])
tensor([50])

One-Dimensional Tensor in Pytorch

In this article, we are going to discuss a one-dimensional tensor in Python. We will look into the following concepts:

  1. Creation of One-Dimensional Tensors
  2. Accessing Elements of Tensor
  3. Size of Tensor
  4. Data Types of Elements of Tensors
  5. View of Tensor
  6. Floating Point Tensor

Introduction

The Pytorch is used to process the tensors. Tensors are multidimensional arrays. PyTorch accelerates the scientific computation of tensors as it has various inbuilt functions.

Vector:

A vector is a one-dimensional tensor that holds elements of multiple data types. We can create vectors using PyTorch. Pytorch is available in the Python torch module. So we need to import it.

Syntax:

import pytorch

Similar Reads

Creation of One-Dimensional Tensors:

One dimensional vector is created using the torch.tensor() method....

Accessing Elements of Tensor:

...

Tensor size:

We can access the elements in the tensor vector using the index of elements....

Data Types of Elements of Tensors:

...

View of Tensor:

This is used to get the length(number of elements)  in a tensor using the size() method....

Floating-point tensor:

...