# Swap cols/rows of a matrix

**URL:** https://discourse.julialang.org/t/swap-cols-rows-of-a-matrix/47904
**Category:** General Usage
**Tags:** matrix
**Created:** [October 6, 2020, 11:33pm UTC](https://discourse.julialang.org/t/swap-cols-rows-of-a-matrix/47904 "2020-10-06T23:33:29Z")
**Posts on this page:** 1
**Showing post:** 7

<div class="post-metadata">

### Author: ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)
#### Post date: [October 7, 2020, 7:05am UTC](https://discourse.julialang.org/t/swap-cols-rows-of-a-matrix/47904/7 "2020-10-07T07:05:19Z")

</div>

> [@lmiq](#):
>
> ```julia
> julia> function swapcol!(x,i,j)
> for k in axes(x)[1]
> idata = x[k,i]
> x[k,i] = x[k,j]
> x[k,j] = idata
> end
> end
> 
> ```

You don’t need the temporary variable:

```julia
function _swapcol!(x,i,j)
    for k in axes(x, 1) # <- give dimension as input to axes function
        x[k, i], x[k, j] = x[k, j], x[k, i]
    end
end

```

If you are reshuffling the columns (or rows) you can supply a vector of indices:

```julia
julia> x = collect(reshape(1:12, 3, 4))
3×4 Array{Int64,2}:
 1 4 7 10
 2 5 8 11
 3 6 9 12

julia> x[:, [2,3,1,4]]
3×4 Array{Int64,2}:
 4 7 1 10
 5 8 2 11
 6 9 3 12

```

---

_[View the full topic](https://discourse.julialang.org/t/swap-cols-rows-of-a-matrix/47904)._
