# Matlab versus Julia

**URL:** <https://discourse.julialang.org/t/matlab-versus-julia/64469>\
**Category:** General Usage\
**Created:** [July 11, 2021, 7:21pm UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469 "2021-07-11T19:21:17Z")\
**Posts on this page:** 14\
**Page:** 2

<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:** [July 11, 2021, 10:39pm UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/21 "2021-07-11T22:39:14Z")

</div>

> [@lmiq](#):
>
> There is a typo there: `as` should be `aa` (my fault on the original post).

No, not one typo. _Two_ typos: `as` and `vc`.

It’s really important to get rid of _all_ the typos.

Also, @asaretto, this is what Matlab was _made_ for. There should not be a big difference between Matlab and Julia on this.

What’s more: this just runs the same simple operation over and over. You should leave those repetitions to your benchmarking tool, don’t do it manually. At worst, the compiler may even decide that it only needs to run _one single_ iteration instead of 100^3, and return a bonkers result.

> [@asaretto](#):
>
> for i = 1:100  
> for j = 1:100  
> for k = 1:100  
> cc = aa.\*bb;  
> end  
> end  
> end  
> end

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [July 11, 2021, 11:03pm UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/22 "2021-07-11T23:03:18Z")

</div>

> [@DNF](#):
>
> , this is what Matlab was _made_ for.

Explicit loops like those are fast in Matlab? (In some specific context or in general?)

---

<div class="post-metadata">

**Author:** ![ParadaCarleton](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/paradacarleton/32/20005_2.png) [@ParadaCarleton](https://discourse.julialang.org/u/ParadaCarleton)\
**Post date:** [July 11, 2021, 11:52pm UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/23 "2021-07-11T23:52:24Z")

</div>

Because compilation wasn’t fully explained earlier in the thread, I’ll go over it in a little bit more detail. The first time you run a function, Julia takes a while because it’s translating it into a well-optimized binary that your computer can read. Matlab translates this function _while_ running it, with very little optimization. This means you don’t have to wait for it to get translated, but any future function calls will be much slower than Julia function calls (assuming identically-written programs).

(Something something this is a [lie to children](https://en.wikipedia.org/wiki/Lie-to-children), but it gets the rough point across.)

---

<div class="post-metadata">

**Author:** ![apo383](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/apo383/32/11272_2.png) [@apo383](https://discourse.julialang.org/u/apo383)\
**Post date:** [July 12, 2021, 12:21am UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/24 "2021-07-12T00:21:37Z")

</div>

Yes, Matlab has made quite big improvements in the [JIT compiler](https://www.mathworks.com/products/matlab/matlab-execution-engine.html), roughly 2015-ish. There was a big jump in performance for certain kinds of loops that used to be glacially slow. Element wise computations for example.

---

<div class="post-metadata">

**Author:** ![blackeneth](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/blackeneth/32/10353_2.png) [@blackeneth](https://discourse.julialang.org/u/blackeneth)\
**Post date:** [July 12, 2021, 1:59am UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/25 "2021-07-12T01:59:19Z")

</div>

Matlab is great. But you pay. Then you pay again. Next, you pay. Then more paying. Finally, you pay.

---

<div class="post-metadata">

**Author:** ![PetrKryslUCSD](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/petrkryslucsd/32/215825_2.png) [@PetrKryslUCSD](https://discourse.julialang.org/u/PetrKryslUCSD)\
**Post date:** [July 12, 2021, 2:15am UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/26 "2021-07-12T02:15:16Z")

</div>

It is a one time payment, paid in annual installments. And after you paid for it, it is entirely free.

---

<div class="post-metadata">

**Author:** ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)\
**Post date:** [July 12, 2021, 3:41am UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/27 "2021-07-12T03:41:40Z")

</div>

Not really. I rented Matlab + addons for 1800 EUR per year for a couple of years, now I cannot use it any more.  
They have different type of licenses.

---

<div class="post-metadata">

**Author:** ![PetrKryslUCSD](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/petrkryslucsd/32/215825_2.png) [@PetrKryslUCSD](https://discourse.julialang.org/u/PetrKryslUCSD)\
**Post date:** [July 12, 2021, 4:54am UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/28 "2021-07-12T04:54:44Z")

</div>

Sorry, 't was a joke (“borrowed” from Portlandia).

---

<div class="post-metadata">

**Author:** ![ParadaCarleton](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/paradacarleton/32/20005_2.png) [@ParadaCarleton](https://discourse.julialang.org/u/ParadaCarleton)\
**Post date:** [July 13, 2021, 9:59pm UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/29 "2021-07-13T21:59:45Z")

</div>

Oh, wow, I didn’t know Matlab was compiled – I thought it was interpreted. Why were loops so slow in the first place then?

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [July 13, 2021, 10:25pm UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/30 "2021-07-13T22:25:09Z")

</div>

Because it’s not just a matter of hooking up a compiler. The semantics of Matlab provide much less information to the compiler than Julia, or any static language, so it’s not always possible to produce _efficient_ compiled code. Retro-fitting a compiler onto a language that was not designed for it is _hard_. (See also Python, which has seen many attempts at compilers.)

That’s why Julia needed a new language, and not just a new compiler. (This is a [FAQ](https://docs.julialang.org/en/v1/manual/faq/#Why-don't-you-compile-Matlab/Python/R/%E2%80%A6-code-to-Julia?). See also [this MIT lecture](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-172-performance-engineering-of-software-systems-fall-2018/lecture-videos/lecture-23-high-performance-in-dynamic-languages/).)

---

<div class="post-metadata">

**Author:** ![dlakelan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dlakelan/32/8491_2.png) [@dlakelan](https://discourse.julialang.org/u/dlakelan)\
**Post date:** [July 13, 2021, 10:53pm UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/31 "2021-07-13T22:53:10Z")

</div>

Also, matlab’s JIT is relatively new 2015 or later.

---

<div class="post-metadata">

**Author:** ![zdenek\_hurak](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/zdenek_hurak/32/53118_2.png) [@zdenek\_hurak](https://discourse.julialang.org/u/zdenek_hurak)\
**Post date:** [July 13, 2021, 11:38pm UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/32 "2021-07-13T23:38:53Z")

</div>

Well, actually some JIT compilation capability was introduced to Matlab much earlier than that – as early as in 2002 (Matlab 6.5):

> MATLAB has employed JIT compilation since release R13 in 2002. The original JIT compiler was designed as a supplement to the MATLAB interpreter, and supported a limited subset of the language…

> **[Run Code Faster With the New MATLAB Execution Engine](https://blogs.mathworks.com/loren/2016/02/12/run-code-faster-with-the-new-matlab-execution-engine/)**
>
> Today I'd like to introduce you to a guest blogger, Dave Bergstein, who is a MATLAB Product Manager here at MathWorks. Today, Dave will be discussing the new MATLAB execution engine.ContentsRedesigned ExecutionWhat It Means For You: Better...

---

<div class="post-metadata">

**Author:** ![brenhinkeller](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/brenhinkeller/32/36648_2.png) [@brenhinkeller](https://discourse.julialang.org/u/brenhinkeller)\
**Post date:** [July 15, 2021, 1:40am UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/33 "2021-07-15T01:40:47Z")

</div>

A bit late to the party, but I like optimizing nested loops in Julia. First, let’s make a version that actually does something distinct on _each_ iteration rather than overwriting the same `cc`:

```julia
aa = rand(Float32,100)
bb = rand(Float32,100)
cc = zeros(Float32,100)
function test!(cc,aa,bb) # Normally the first argument is the mutated one
    for i = 1:100
        for j = 1:100
            for k = 1:100
                cc[i] += aa[j] * bb[k]
            end
        end
    end
    return cc # Optional, but doesn't cost anything
end

```

For benchmarking, I heavily recommend something that will give you a histogram rather than a single number. For example:

```julia
julia> using BenchmarkTools

julia> @benchmark test!($cc,$aa,$bb)
BechmarkTools.Trial: 1757 samples with 1 evaluations.
 Range (min … max): 2.435 ms … 5.037 ms ┊ GC (min … max): 0.00% … 0.00%
 Time (median): 2.671 ms ┊ GC (median): 0.00%
 Time (mean ± σ): 2.836 ms ± 445.603 μs ┊ GC (mean ± σ): 0.00% ± 0.00%

  ▄█▅▇▆▄▆▂▁▁                                                   
  ██████████▇▅▆▄▅▄▅▄▄▄▃▃▃▃▄▃▃▃▃▃▃▃▃▃▂▃▂▂▂▂▂▂▂▂▂▂▂▂▂▂▃▂▂▂▁▂▂▂▂ ▄
  2.44 ms Histogram: frequency by time 4.54 ms <

 Memory estimate: 0 bytes, allocs estimate: 0.

```

Note that if benchmarking in global scope (like the REPL), you need to use `$` to interpolate global variables into the benchmark.

This isn’t terrible, and there’s no allocations which is good, but one can get _much_ faster. In particular, by using your CPU’s SIMD vector registers and instructions, which for this example you can easily do with the amazing [LoopVectorization.jl](https://github.com/JuliaSIMD/LoopVectorization.jl)

```julia
using LoopVectorization
function test_lv!(cc,aa,bb) # Normally the first argument is the mutated one
    @turbo for i = 1:100
        for j = 1:100
            for k = 1:100
                cc[i] += aa[j] * bb[k]
            end
        end
    end
    return cc # Optional, but doesn't cost anything
end

```

which gives us

```julia
julia> @benchmark test_lv!($cc,$aa,$bb)
BechmarkTools.Trial: 10000 samples with 1 evaluations.
 Range (min … max): 106.252 μs … 453.916 μs ┊ GC (min … max): 0.00% … 0.00%
 Time (median): 106.263 μs ┊ GC (median): 0.00%
 Time (mean ± σ): 110.554 μs ± 16.103 μs ┊ GC (mean ± σ): 0.00% ± 0.00%

  █▁ ▃ ▃ ▃ ▁ ▁
  ██▄▄█▆▇▅▅▆▅█▆▆▄▅▆▅▄▃█▅▆▅▅▅▅▃▄▄▄▅▁▁▃▃▄▃▃▄▁▁▁▃▁▁▃▃▃▁▄▃▁▄▁▁▁▃▁▁█ █
  106 μs Histogram: log(frequency) by time 206 μs <

 Memory estimate: 0 bytes, allocs estimate: 0.

```

That’s more than a 20x speedup, and would likely be even better on a computer with AVX512 (I only have AVX2). That’s a bit more of a speedup than typical for LV for (e.g.)` Float64`s, but you can fit 2x as many `Float32`s in a given vector register, so SIMD vectorization may matter more for smaller number types.

Finally, since Matlab tries to multithread by default, why don’t we do the same to level the playing field (it just takes an extra `t` in the macro name)

```julia
function test_lvt!(cc,aa,bb) # Normally the first argument is the mutated one
    @tturbo for i = 1:100
        for j = 1:100
            for k = 1:100
                cc[i] += aa[j] * bb[k];
            end
        end
    end
    return cc # Optional, but doesn't cost anything
end

```

This gives about another 4x speedup (on a 4 core CPU) despite the small problem size because of the very lightweight threading (from [Polyester.jl](https://github.com/JuliaSIMD)) used by by `@tturbo`.

```julia
julia> @benchmark test_lvt!($cc,$aa,$bb)
BechmarkTools.Trial: 10000 samples with 1 evaluations.
 Range (min … max): 26.804 μs … 96.401 μs ┊ GC (min … max): 0.00% … 0.00%
 Time (median): 26.919 μs ┊ GC (median): 0.00%
 Time (mean ± σ): 27.389 μs ± 2.680 μs ┊ GC (mean ± σ): 0.00% ± 0.00%

  █▄▁ ▁ ▁
  ███▆▅▇▇▇█▆▅▄▆▄▅▄▄▄▃▃▁▁▃▄▄▄▁▄▅▅▅▆▆▇▆▆▆▆▄▅▅▆▄▅▄▄▃▃▄▄▄▅▆▄▄▄▄▅▅ █
  26.8 μs Histogram: log(frequency) by time 40 μs <

 Memory estimate: 0 bytes, allocs estimate: 0.

```

---

<div class="post-metadata">

**Author:** ![brenhinkeller](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/brenhinkeller/32/36648_2.png) [@brenhinkeller](https://discourse.julialang.org/u/brenhinkeller)\
**Post date:** [July 15, 2021, 1:43am UTC](https://discourse.julialang.org/t/matlab-versus-julia/64469/34 "2021-07-15T01:43:06Z")

</div>

Since you mention coming from Matlab @asaretto, my own two cents after making the same transition: [GitHub - brenhinkeller/JuliaAdviceForMatlabProgrammers: Learning to love dispatch-oriented programming](https://github.com/brenhinkeller/JuliaAdviceForMatlabProgrammers)

You can also feel free to ask julia-matlab questions or start discussions in the #matlabsconders channels on Slack or Zulip (pretty quiet channels, but will have a few who have made the transition lurking)

[Previous page](https://discourse.julialang.org/t/matlab-versus-julia/64469.md?page=1)
