## Transpose A Matrix In PyTorch

Transpose A Matrix In PyTorch by using the PyTorch T operation

### < > Code:

You must be a Member to view the code for this video.

or Log In

Subscribe today and get access to all lessons and their code and transcripts!

### Transcript:

This video will show you how to transpose a matrix in PyTorch by using the PyTorch t operation.

To get started, let’s import PyTorch.

```
import torch
```

We print the PyTorch version we are using.

```
print(torch.__version__)
```

We are using PyTorch 0.3.1.post2.

Let’s now create our PyTorch matrix by using the torch.Tensor operation.

```
pt_matrix_ex = torch.Tensor(
[
[1, 2, 3],
[0, 0, 0],
[4, 5, 6]
])
```

The data structure will be this 3x3 matrix where the first row is 1, 2, 3, second row is 0, 0, 0, third row is 4, 5, 6.

Let’s print the pt_matrix_ex Python variable to see what we have.

```
print(pt_matrix_ex)
```

So we see that the first row is 1, 2, 3, second row is 0, 0, 0, third row is 4, 5, 6.

It’s a torch.FloatTensor of size 3x3.

To do the PyTorch matrix transpose, we’re going to use the PyTorch t operation.

So we use our initial PyTorch matrix, and then we say dot t, open and close parentheses, and we assign the result to the Python variable pt_transposed_matrix_ex.

```
pt_transposed_matrix_ex = pt_matrix_ex.t()
```

Let’s print the pt_transposed_matrix_ex Python variable to see what we have.

```
print(pt_transposed_matrix_ex)
```

We see that our original matrix has been transposed which means that the numbers 1, 2, 3 now go down as the first column, 1, 2, 3.

The numbers in the second row, 0, 0, 0 are now the second column, 0, 0, 0.

The numbers in the third row, 4, 5, 6 are now the numbers in the third column, 4, 5, 6.

Note that because we didn’t use an underscore after the t, it means that we’ve left our initial pt_matrix_ex the same.

So we didn’t do an in-place operation.

So when we did t, this t generated a new tensor which was what was assigned to the pt_transposed_matrix_ex.

So when we print pt_matrix which was our original matrix, we see that it was left untouched.

```
print(pt_matrix_ex)
```

Perfect - We were able to transpose a matrix in PyTorch by using the PyTorch t operation.