# Using Matlab from Julia

**URL:** <https://discourse.julialang.org/t/using-matlab-from-julia/105451>\
**Category:** General Usage\
**Tags:** question, package\
**Created:** [October 26, 2023, 4:53pm UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451 "2023-10-26T16:53:30Z")\
**Posts on this page:** 11\
**Page:** 1

<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:** [October 26, 2023, 4:53pm UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/1 "2023-10-26T16:53:30Z")

</div>

I am testing the package MATLAB.jl.

This works:

```julia
using MATLAB
mat"1+1"

```

This doesn’t work:

```julia
julia> mat"tf([1],[1,1])"
ERROR: ArgumentError: Unsupported kind of variable.
Stacktrace:
 [1] jvalue(mx::MxArray)
   @ MATLAB C:\Users\uwefechner\.julia\packages\MATLAB\xBhSu\src\mxarray.jl:650
 [2] get_variable(name::Symbol)
   @ MATLAB C:\Users\uwefechner\.julia\packages\MATLAB\xBhSu\src\engine.jl:170
 [3] top-level scope
   @ C:\Users\uwefechner\.julia\packages\MATLAB\xBhSu\src\matstr.jl:169

```

This command is working in Matlab directly, though.

Testing on Windows, Matlab 2021a, Julia 1.9.3.

Any idea?

---

<div class="post-metadata">

**Author:** ![Palli](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/palli/32/3380_2.png) [@Palli](https://discourse.julialang.org/u/Palli)\
**Post date:** [October 26, 2023, 5:29pm UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/2 "2023-10-26T17:29:42Z")

</div>

It seems the return value is of a MATLAB type that MATLAB.jl does not support (it only supports the basics), and I don’t recall what those types might be.

It’s been a while since I used it, and I no longer have MATLAB, but you can use all of MATLAB at the MATLAB side, including all the types, but not send all the types back and forth.

> <https://github.com/JuliaInterop/MATLAB.jl/blob/fb1bc5af1ba7bfd98eea4c869a13d8fa0c080274/src/mxarray.jl#L650>

another plausible (no longer believe that) I had copied while lookup of for you:

> If the MATLAB function is not in the current directory, we need to first add it to the MATLAB path before calling through Julia:  
> mat"addpath(‘/path/to/folder’)"

I recall type troubles, and what you could plausible do is make a wrapper function at MATLAB, that converts to appropriate type/format or summarizes somehow, if enough and returns just that (type).

FYI: you can also call Octave, the MATLAB clone. I did both. I used that package and MATLAB, but not for Octave.

If I recall, if you use MATLAB, the license disallows using it to help migrate code…

I was porting/migrating MATLAB code from MATLAB to Julia. They can’t dictate how Octave, and your _own MATLAB source code_ is used, with it.

The Julia project to call Octave was immature, at least at the time, but the one to call from Python and to Octave wasn’t (not Julia default to many BLAS threads, I had to disable that, not because of the Julia side, but because of Octave which didn’t support, with some ENV var). Nor is to call Python, so to it, and to Octave (to run MATLAB code)…

There’s also a MATLAB to Julia transpiler/compiler available. It worked, sort of, not for all syntax, helped with some. Not all the semantics are the same either. If you use MATLAB well, it might not be very valuable. And toolboxes are a problem. I recommend calling, i.e. reusing code if it works for you, in Octave, rather that porting. If it’s missing toolboxes then a problem and pros and cons to reusing vs. porting.

---

<div class="post-metadata">

**Author:** ![vettert](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vettert/32/30599_2.png) [@vettert](https://discourse.julialang.org/u/vettert)\
**Post date:** [October 26, 2023, 5:39pm UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/3 "2023-10-26T17:39:47Z")

</div>

According to the Matlab documentation ([Transfer function model - MATLAB](https://www.mathworks.com/help/control/ref/tf.html)) the tf(.) function returns a model object. That sounds like a rather complex (in the sense of non-trivial) type.

So, my first thought is that it’s not that surprising that Julia doesn’t know what to do with it?

---

<div class="post-metadata">

**Author:** ![Palli](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/palli/32/3380_2.png) [@Palli](https://discourse.julialang.org/u/Palli)\
**Post date:** [October 26, 2023, 5:52pm UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/4 "2023-10-26T17:52:11Z")

</div>

Right, it’s:

> `tf` model object | `genss` model object | `uss` model object

and I’m guessing those are objects, i.e. of a class; MATLAB is object oriented by now, as many languages even COBOL and Fortran. MATLAB.jl doesn’t support objects, maybe it would not be too hard to add some capability to get back somehow? If not there, then you use its “getters” to get data out…

I suppose MATLAB.jl shouldn’t get the data from the object, that would be one way, and break encapsulation, rather just give you an object pointer, likely rather trivial. And then some way to access methods of that object, less trivial but also then needed. So a distributed objects…

[Reminds of of the intriguing (distributed) Unison language, and the great StrangeLoop talk on it I was just watching on Youtube (the AST, not text, and hashing of it was the intriguing part, for immutability/distributed reasons).]

---

<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:** [October 26, 2023, 5:59pm UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/5 "2023-10-26T17:59:09Z")

</div>

Well, it could just return the string representation… That should be trivial, shouldn’t it?

I thought that the way I passed the input parameters would be wrong. Good to hear that this is not the problem.

In the end, the Julia [ControlSystems.jl](https://github.com/JuliaControl/ControlSystems.jl) library has the same sort of object, so in the ideal case it should be converted to that. Not difficult, just a call to the `tf` function with two parameters, the nominator and the denominator vector… (or array?)

---

<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:** [October 27, 2023, 9:56am UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/6 "2023-10-27T09:56:53Z")

</div>

I am pretty happy with my current wrapper for the matlab function `simplify`:  
(This is the only function I found so far that is much more efficient in Matlab than in Julia.)

```julia
using ModelingToolkit, MATLAB
@variables t ω Pg Pge Pgc Uest
@variables R a b c d Γ ρ U J Q Qest V A Ku Γest λ λest λnom s Kp Ki Cs

function matlab2julia(str)
     res = replace(str, "rho" => "ρ")
     res = replace(res, "Gamma" => "Γ")
     res = replace(res, "omega" => "ω")
     res = replace(res, "lambda_nom" => "λnom")
     eval(Meta.parse(res))
end
function julia2matlab(str)
     res = replace(str, "ρ" =>"rho")
     res = replace(res, "Γ" => "Gamma")
     res = replace(res, "ω" => "omega")
     res = replace(res, "λnom" => "lambda_nom")
     res = replace(res, "1.5A" => "1.5*A")
     res = replace(res, "0.5A" => "0.5*A")
end

function simplify_m(expr::Num)
     mat"syms t omega Pg Pge Pgc Uest"
     mat"syms R a b c d Gamma rho U J Q Qest V A Ku lambda_nom s Kp Ki Cs"
     sexpr = repr(expr)
     orig = length(sexpr)
     sexpr = julia2matlab(sexpr)
     mat"expr=str2sym($sexpr);"
     mat"expr=simplify(expr);"
     res = mat"convertContainedStringsToChars(string(expr))"
     res = matlab2julia(res)
     println("Simplified expression from $orig to $(length(repr(res))) characters!")
     res
end

expr = (Q - Qest)*(((1.5A*(U^2)*b*Γ*ρ + A*R*U*a*Γ*ρ*ω)*(s + Ku*V)*s) / (J*((Kp*Ku*(Q - Qest)*s*λnom))))
sexpr = simplify_m(expr)

```

Question: Any idea how to write this in a more generic way:

```julia
 res = replace(res, "1.5A" => "1.5*A")
 res = replace(res, "0.5A" => "0.5*A")
...

```

Matlab needs the “\*” for multiplication, but Julia is not providing it. So it would be nice to have a function that inserts it everywhere where it is needed…

---

<div class="post-metadata">

**Author:** ![lmshk](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmshk/32/29632_2.png) [@lmshk](https://discourse.julialang.org/u/lmshk)\
**Post date:** [October 28, 2023, 1:56pm UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/7 "2023-10-28T13:56:58Z")

</div>

As a first step you could collapse the `replace` calls into a single one, e.g.:

```julia
julia2matlab(str) = replace(
    str,
    "ρ" =>"rho",
    "Γ" => "Gamma",
    #= ... =#
)

```

If I understand you correctly, by “more generic” you mean something like:

```julia
replace("some code with 1.5A;", r"(\d+\.\d+)A" => s"\1*A")
# "some code with 1.5*A;"

```

See `?@s_str` and `?replace` (and note that “Support for multiple patterns requires version 1.7.”).

Of course there are many cases where this kind of text-to-text code translation will fail.

---

<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:** [November 1, 2023, 9:57am UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/8 "2023-11-01T09:57:46Z")

</div>

> [@lmshk](#):
>
> ?@s\_str

I got already quite far, but now I am stuck with replacing 2( with 2\*( using regular expressions:

```julia
using Symbolics

@variables R a b c d Γ ρ U J Q Qest V A Ku Γest λ λest λnom s Kp Ki Cs

input1 = (2U + 0.5U*b + 4.0U*c)
input2 = (2A + 0.5A*b + 4.0A*c + 2(a + b))

function julia2matlab(str)
    res = str
    for symbol in ["A", "U"]
        res = replace(res, Regex("(\\d+\\.\\d+)$symbol") => SubstitutionString("\\1*$symbol"))
        res = replace(res, Regex("(\\d+)$symbol") => SubstitutionString("\\1*$symbol"))
    end
    # res = replace(res, Regex("(\\d+)\\(") => SubstitutionString("\\1*\\("))
    res
end

mstring = julia2matlab(repr(input1))
println(mstring)
@assert mstring == "2*U + 0.5*U*b + 4.0*U*c"
mstring = julia2matlab(repr(input2))
println(mstring)
@assert mstring == "2*A + 2*(a + b) + 0.5*A*b + 4.0*A*c"

```

The commented line fails. What am I doing wrong?

If I do:

```julia
res = replace(res, r("(\d+)\(") => s("\1*\("))

```

I get the error:

```julia
julia> include("mwes/mwe19.jl")
ERROR: LoadError: syntax: invalid escape sequence
Stacktrace:
 [1] top-level scope
   @ ~/repos/WindTurbines/mwes/mwe19.jl:14
 [2] include(fname::String)
   @ Base.MainInclude ./client.jl:478
 [3] top-level scope
   @ REPL[37]:1
in expression starting at /home/ufechner/repos/WindTurbines/mwes/mwe19.jl:14

```

---

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [November 1, 2023, 1:59pm UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/9 "2023-11-01T13:59:00Z")

</div>

The immediate problem is that you can’t add parentheses around a string macro. `r"..."` provides special parsing whereas `r("...")` does normal string parsing and then passes the string to a function `r` (which you probably hadn’t defined).

Maybe this helps:

```julia
julia> replace("2(", r"(\d+)\(" => s"\1*(")
"2*("

```

---

<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:** [November 1, 2023, 2:42pm UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/10 "2023-11-01T14:42:05Z")

</div>

Thanks, this helped. So I need to escape the bracket when using an `r""`, but not when using `s"" `, correct?

---

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [November 1, 2023, 2:47pm UTC](https://discourse.julialang.org/t/using-matlab-from-julia/105451/11 "2023-11-01T14:47:43Z")

</div>

I don’t have more insights than “yes, it looks like that”. But it seems reasonable to me that a regex needs more syntactical constructs and thus more escaping than a substitution string.
