YouTip LogoYouTip

Pytorch Torch Searchsorted

* * Pytorch torch Reference Manual](#) `torch.searchsorted` is a function in PyTorch used to search for the insertion positions of elements in a sorted tensor. The returned value is the index position where the element should be inserted. ### Function Definition torch.searchsorted(sorted_sequence, values, side='left', out_int32=False, right=False) Parameter description: * `sorted_sequence`: a sorted one-dimensional or multi-dimensional tensor * `values`: the values to search for * `side`: 'left' or 'right', determines whether to return the left or right insertion position * `out_int32`: whether to return int32 type * `right`: deprecated, use side instead * * * ## Usage Examples ## Example import torch # Create sorted sequence sorted_seq = torch.tensor([1,3,5,7,9]) # Search for positions of values values = torch.tensor([3,6,8]) y = torch.searchsorted(sorted_seq, values) print(y) Output result: tensor([1, 3, 3])

Example

import torch

# Create sorted sequence
sorted_seq = torch.tensor([1, 3, 5, 7, 9])

# Search using side='right'
values = torch.tensor([3, 6, 8])
y = torch.searchsorted(sorted_seq, values, side='right')
print(y)

Output result:

 tensor([2, 3, 4])

## Example

import torch

# For multi-dimensional arrays

 sorted_seq = torch.tensor([[1,3,5],[2,4,6]])

 values = torch.tensor([[1.5],[3.5]])

 y = torch.searchsorted(sorted_seq, values)

print(y)

Output result:

tensor([, ])

* * Pytorch torch Reference Manual](#)
← Pytorch Torch SelectPytorch Torch Scatter_Add β†’