# What is the fastest method to shift matrix?

**URL:** <https://discourse.julialang.org/t/what-is-the-fastest-method-to-shift-matrix/85261>\
**Category:** General Usage\
**Tags:** question\
**Created:** [August 3, 2022, 7:33pm UTC](https://discourse.julialang.org/t/what-is-the-fastest-method-to-shift-matrix/85261 "2022-08-03T19:33:10Z")\
**Posts on this page:** 1\
**Showing post:** 27

<div class="post-metadata">

**Author:** ![acxz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/acxz/32/16759_2.png) [@acxz](https://discourse.julialang.org/u/acxz)\
**Post date:** [August 4, 2022, 5:03pm UTC](https://discourse.julialang.org/t/what-is-the-fastest-method-to-shift-matrix/85261/27 "2022-08-04T17:03:38Z")

</div>

Updated MWE:

```julia
using BenchmarkTools
using LinearAlgebra
using SparseArrays
using Random

function trie()
    row_dim = 44
    col_dim = 33
    A_density = 0.2679063360881543
    rng = MersenneTwister(1)

    A = sprand(rng, row_dim, col_dim, A_density)
    B = sprand(rng, row_dim, col_dim, A_density)

    # Matrix mult
    shift = spdiagm(-1 => ones(size(A, 2) - 1))

    for _ in 1:24001
        # Matrix mult
        A .= A * shift .+ B

        # Slicing
        A[:, 1] .= 0
        dropzeros!(A)
        A[1:size(A, 1), vcat(2:size(A, 2), 1)]
        A .+= B
    end

end

```

Results in order of method:

```julia
julia> include("shift_sparse.jl")
BenchmarkTools.Trial: 16 samples with 1 evaluation.
 Range (min … max): 301.004 ms … 324.754 ms ┊ GC (min … max): 4.78% … 4.60%
 Time (median): 317.756 ms ┊ GC (median): 4.59%
 Time (mean ± σ): 317.456 ms ± 5.221 ms ┊ GC (mean ± σ): 4.60% ± 0.13%

  ▁ ▁ ▁ ▁▁ ▁█▁ ▁▁▁▁ ▁▁ ▁  
  █▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█▁▁█▁▁██▁███▁▁████▁▁▁██▁▁▁▁▁█ ▁
  301 ms Histogram: frequency by time 325 ms <

 Memory estimate: 1.13 GiB, allocs estimate: 144044.

julia> include("shift_sparse.jl")
BenchmarkTools.Trial: 28 samples with 1 evaluation.
 Range (min … max): 175.798 ms … 184.465 ms ┊ GC (min … max): 5.95% … 5.29%
 Time (median): 179.539 ms ┊ GC (median): 5.99%
 Time (mean ± σ): 180.077 ms ± 2.321 ms ┊ GC (mean ± σ): 5.94% ± 0.34%

                     █ █ ▃  
  ▇▁▁▇▁▁▁▁▁▁▁▁▇▁▁▁▇▇▇█▇█▁▁▇▁▁▁▇▇▇▁▇▁▁▁▁▇▁▇▁▇▁▇▁▁▇▁▇▁▁▇▁▁▁▁▇▁▁▁█ ▁
  176 ms Histogram: frequency by time 184 ms <

 Memory estimate: 509.46 MiB, allocs estimate: 168029.

```

---

_[View the full topic](https://discourse.julialang.org/t/what-is-the-fastest-method-to-shift-matrix/85261)._
