Giter Site home page Giter Site logo

matlab.jl's Introduction

MATLAB

❗ Windows and MacOS platforms : MATLAB versions R2022 and R2023 do not work with MATLAB.jl
You can use older versions as explained further down.

The MATLAB.jl package provides an interface for using MATLAB® from Julia using the MATLAB C api. In other words, this package allows users to call MATLAB functions within Julia, thus making it easy to interoperate with MATLAB from the Julia language.

You cannot use MATLAB.jl without having purchased and installed a copy of MATLAB® from MathWorks. This package is available free of charge and in no way replaces or alters any functionality of MathWorks's MATLAB product.

Overview

This package is composed of two aspects:

  • Creating and manipulating mxArrays (the data structure that MATLAB used to represent arrays and other kinds of data)

  • Communicating with MATLAB engine sessions

Warning:

  • MATLAB string arrays are not supported, and will throw an error exception. This also applies if they are nested within a MATLAB struct. This is a limitation of the MATLAB C api. The MATLAB function convertContainedStringsToChars may be used to facilitate conversion to a compatible format for use with MATLAB.jl.

  • Threading is also not supported within Julia when using the MATLAB.jl library.

Installation

Important: The procedure to setup this package consists of the following steps.

Windows

  1. For Matlab R2020a onwards, you should be able to go directly to step 2. If you encounter issues, run matlab -batch "comserver('register')" in the command prompt. For earlier versions of Matlab, start a command prompt as an administrator and enter matlab /regserver.

  2. From Julia run: Pkg.add("MATLAB")

Linux

  1. Make sure matlab is in executable path.

  2. Make sure csh is installed. (Note: MATLAB for Linux relies on csh to open an engine session.)

    To install csh in Debian/Ubuntu/Linux Mint, you may type in the following command in terminal:

    sudo apt-get install csh
  3. From Julia run: Pkg.add("MATLAB")

If you experience problems when starting the MATLAB engine with versions R2022 or R2023, try to update your MATLAB release.

Mac OS X

  1. Ensure that MATLAB is installed in /Applications (for example, if you are using MATLAB R2012b, you may add the following command to .profile: export MATLAB_HOME=/Applications/MATLAB_R2012b.app).

  2. From Julia run: Pkg.add("MATLAB")

Changing MATLAB version

By default, MATLAB.jl is built using the MATLAB installation with the greatest version number. To specify that a specific MATLAB installation should be used, set the environment variable MATLAB_ROOT:

julia> ENV["MATLAB_ROOT"] = "/usr/local/MATLAB/R2021b" # example on a Linux machine
julia> ENV["MATLAB_ROOT"] = raw"C:\Program Files\MATLAB\R2021b" # example on a Windows machine

Replace the path string with the location of the MATLAB folder on your machine. You need to set the path to the R20XX folder, not the matlab binary.

If you had the package MATLAB.jl already installed and built before changing the environment variable, you will need to rebuild it to apply the change:

julia> using Pkg; Pkg.build("MATLAB")

Usage

MxArray class

An instance of MxArray encapsulates a MATLAB variable. This package provides a series of functions to manipulate such instances.

Create MATLAB variables in Julia

One can use the function mxarray to create MATLAB variables (of type MxArray), as follows

mxarray(Float64, n)   # creates an n-by-1 MATLAB zero array of double valued type
mxarray(Int32, m, n)  # creates an m-by-n MATLAB zero array of int32 valued type
mxarray(Bool, m, n)   # creates a MATLAB logical array of size m-by-n

mxarray(Float64, (n1, n2, n3))  # creates a MATLAB array of size n1-by-n2-by-n3

mxcellarray(m, n)        # creates a MATLAB cell array
mxstruct("a", "b", "c")  # creates a MATLAB struct with given fields

You may also convert a Julia variable to MATLAB variable

a = rand(m, n)

x = mxarray(a)     # converts a to a MATLAB array
x = mxarray(1.2)   # converts a scalar 1.2 to a MATLAB variable

a = sprand(m, n, 0.1)
x = mxarray(a)     # converts a sparse matrix to a MATLAB sparse matrix

x = mxarray("abc") # converts a string to a MATLAB char array

x = mxarray(["a", 1, 2.3])  # converts a Julia array to a MATLAB cell array

x = mxarray(Dict("a"=>1, "b"=>"string", "c"=>[1,2,3])) # converts a Julia dictionary to a MATLAB struct

The function mxarray can also convert a compound type to a Julia struct:

struct S
    x::Float64
    y::Vector{Int32}
    z::Bool
end

s = S(1.2, Int32[1, 2], false)

x = mxarray(s)   # creates a MATLAB struct with three fields: x, y, z
xc = mxarray([s, s])  # creates a MATLAB cell array, each cell is a struct.
xs = mxstructarray([s, s])  # creates a MATLAB array of structs

Note: For safety, the conversation between MATLAB and Julia variables uses deep copy.

When you finish using a MATLAB variable, you may call delete to free the memory. But this is optional, it will be deleted when reclaimed by the garbage collector.

delete(x)

Note: if you put a MATLAB variable x to MATLAB engine session, then the MATLAB engine will take over the management of its life cylce, and you don't have to delete it explicitly.

Access MATLAB variables

You may access attributes and data of a MATLAB variable through the functions provided by this package.

# suppose x is of type MxArray
nrows(x)    # returns number of rows in x
ncols(x)    # returns number of columns in x
nelems(x)   # returns number of elements in x
ndims(x)    # returns number of dimensions in x
size(x)     # returns the size of x as a tuple
size(x, d)  # returns the size of x along a specific dimension

eltype(x)   # returns element type of x (in Julia Type)
elsize(x)   # return number of bytes per element

data_ptr(x)   # returns pointer to data (in Ptr{T}), where T is eltype(x)

# suppose s is a MATLAB struct
mxnfields(s)	# returns the number of fields in struct s

You may also make tests on a MATLAB variable.

is_double(x)   # returns whether x is a double array
is_sparse(x)   # returns whether x is sparse
is_complex(x)  # returns whether x is complex
is_cell(x)     # returns whether x is a cell array
is_struct(x)   # returns whether x is a struct
is_empty(x)    # returns whether x is empty

...            # there are many more there

Convert MATLAB variables to Julia

a = jarray(x)   # converts x to a Julia array
a = jvector(x)  # converts x to a Julia vector (1D array) when x is a vector
a = jscalar(x)  # converts x to a Julia scalar
a = jmatrix(x)  # converts x to a Julia matrix
a = jstring(x)  # converts x to a Julia string
a = jdict(x)    # converts a MATLAB struct to a Julia dictionary (using fieldnames as keys)

a = jvalue(x)  # converts x to a Julia value in default manner

Read/Write MAT Files

This package provides functions to manipulate MATLAB's mat files:

mf = MatFile(filename, mode)    # opens a MAT file using a specific mode, and returns a handle
mf = MatFile(filename)          # opens a MAT file for reading, equivalent to MatFile(filename, "r")
close(mf)                       # closes a MAT file.

get_mvariable(mf, name)   # gets a variable and returns an mxArray
get_variable(mf, name)    # gets a variable, but converts it to a Julia value using `jvalue`

put_variable(mf, name, v)   # puts a variable v to the MAT file
                            # v can be either an MxArray instance or normal variable
                            # If v is not an MxArray, it will be converted using `mxarray`

put_variables(mf; name1=v1, name2=v2, ...)  # put multiple variables using keyword arguments

variable_names(mf)   # get a vector of all variable names in a MAT file

There are also convenient functions that can get/put all variables in one call:

read_matfile(filename)    # returns a dictionary that maps each variable name
                          # to an MxArray instance

write_matfile(filename; name1=v1, name2=v2, ...)  # writes all variables given in the
                                                  # keyword argument list to a MAT file

Both read_matfile and write_matfile will close the MAT file handle before returning.

Examples:

struct S
    x::Float64
    y::Bool
    z::Vector{Float64}
end

write_matfile("test.mat";
    a = Int32[1 2 3; 4 5 6],
    b = [1.2, 3.4, 5.6, 7.8],
    c = [[0.0, 1.0], [1.0, 2.0], [1.0, 2.0, 3.0]],
    d = Dict("name"=>"MATLAB", "score"=>100.0),
    s = "abcde",
    ss = [S(1.0, true, [1., 2.]), S(2.0, false, [3., 4.])] )

This example will create a MAT file called test.mat, which contains six MATLAB variables:

  • a: a 2-by-3 int32 array
  • b: a 4-by-1 double array
  • c: a 3-by-1 cell array, each cell contains a double vector
  • d: a struct with two fields: name and score
  • s: a string (i.e. char array)
  • ss: an array of structs with two elements, and three fields: x, y, and z.

Use MATLAB Engine

Basic Use

To evaluate expressions in MATLAB, one may open a MATLAB engine session and communicate with it. There are three ways to call MATLAB from Julia:

  • The mat"" custom string literal allows you to write MATLAB syntax inside Julia and use Julia variables directly from MATLAB via interpolation
  • The eval_string evaluate a string containing MATLAB expressions (typically used with the helper macros @mget and @mput
  • The mxcall function calls a given MATLAB function and returns the result

In general, the mat"" custom string literal is the preferred method to interact with the MATLAB engine.

Note: There can be multiple (reasonable) ways to convert a MATLAB variable to Julia array. For example, MATLAB represents a scalar using a 1-by-1 matrix. Here we have two choices in terms of converting such a matrix back to Julia: (1) convert to a scalar number, or (2) convert to a matrix of size 1-by-1.

The mat"" custom string literal

Text inside the mat"" custom string literal is in MATLAB syntax. Variables from Julia can be "interpolated" into MATLAB code by prefixing them with a dollar sign as you would interpolate them into an ordinary string.

using MATLAB

x = range(-10.0, stop=10.0, length=500)
mat"plot($x, sin($x))"  # evaluate a MATLAB function

y = range(2.0, stop=3.0, length=500)
mat"""
    $u = $x + $y
	$v = $x - $y
"""
@show u v               # u and v are accessible from Julia

As with ordinary string literals, you can also interpolate whole Julia expressions, e.g. mat"$(x[1]) = $(x[2]) + $(binomial(5, 2))".

eval_string

You may also use the eval_string function to evaluate MATLAB code as follows

eval_string("a = sum([1,2,3])")

The eval_string function also takes an optional argument that specifies which MATLAB session to evaluate the code in, e.g.

julia> s = MSession();
julia> eval_string(s, "a = sum([1,2,3])")
a =
     6
mxcall

You may also directly call a MATLAB function on Julia variables using mxcall:

x = -10.0:0.1:10.0
y = -10.0:0.1:10.0
xx, yy = mxcall(:meshgrid, 2, x, y)

Note: Since MATLAB functions behavior depends on the number of outputs, you have to specify the number of output arguments in mxcall as the second argument.

mxcall puts the input arguments to the MATLAB workspace (using mangled names), evaluates the function call in MATLAB, and retrieves the variable from the MATLAB session. This function is mainly provided for convenience. However, you should keep in mind that it may incur considerable overhead due to the communication between MATLAB and Julia domain.

@mget and @mput

The macro @mget can be used to extract the value of a MATLAB variable into Julia

julia> mat"a = 6"
julia> @mget a
6.0

The macro @mput can be used to translate a Julia variable into MATLAB

julia> x = [1,2,3]
julia> @mput x
julia> eval_string("y = sum(x)")
julia> @mget y
6.0
julia> @show y
a = 63.0

Calling custom MATLAB function

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')"
val = mat"myfunction($arg1, $arg2)"

For example, if there is a MATLAB file located at /path/to/folder with contents:

function [r,u] = test(x, y)
	r = x + y;
	u = x - y;
end

We can call this function as follows in Julia:

using MATLAB

x = range(-10.0, stop=10.0, length=500)
y = range(2.0, stop=3.0, length=500)

mat"addpath('/path/to/folder')"

r, u = mxcall(:test,2,x,y)

Viewing the MATLAB Session (Windows only)

To open an interactive window for the MATLAB session, use the command show_msession() and to hide the window, use hide_msession(). Warning: manually closing this window will result in an error or result in a segfault; it is advised that you only use the hide_msession() command to hide the interactive window.

Note that this feature only works on Windows.

# default
show_msession() # open the default MATLAB session interactive window
get_msession_visiblity() # get the session's visibility state
hide_msession() # hide the default MATLAB session interactive window

# similarly
s = MSession()
show_msession(s)
get_msession_visiblity(a)
hide_msession(s)

Advanced use of MATLAB Engines

This package provides a series of functions for users to control the communication with MATLAB sessions.

Here is an example:

s1 = MSession()    # creates a MATLAB session
s2 = MSession(0)   # creates a MATLAB session without recording output

x = rand(3, 4)
put_variable(s1, :x, x)  # put x to session s1

y = rand(2, 3)
put_variable(s2, :y, y)  # put y to session s2

eval_string(s1, "r = sin(x)")  # evaluate sin(x) in session s1
eval_string(s2, "r = sin(y)")  # evaluate sin(y) in session s2

r1_mx = get_mvariable(s1, :r)  # get r from s1
r2_mx = get_mvariable(s2, :r)  # get r from s2

r1 = jarray(r1_mx)
r2 = jarray(r2_mx)

# ... do other stuff on r1 and r2

close(s1)  # close session s1
close(s2)  # close session s2

matlab.jl's People

Contributors

alexanderulanowski avatar bolognam avatar chrisrackauckas avatar dawbarton avatar dhr avatar egavazzi avatar github-actions[bot] avatar jdlangs avatar jfsantos avatar juliatagbot avatar kevin-mattheus-moerman avatar lindahua avatar mbauman avatar musm avatar pallharaldsson avatar pitsianis avatar pratyai avatar shield-sky avatar simonster avatar sjkelly avatar spaette avatar stefankarpinski avatar taylormcd avatar thomas-nilsson-irfu avatar timholy avatar tkelman avatar twadleigh avatar vsaase avatar waldyrious avatar yuyichao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

matlab.jl's Issues

MATLAB.jl: Print Output during evaluation in MATLAB

Hi,

I have a certain function in matlab say: Star(filename)
when I run `Star' via Matlab it prints code progress as it runs. It takes a while to run and hence it prints some progress to the Maltab prompt after fixed time intervals.

Now when I run the following code in Julia REPL

using MATLAB;
S = MSession();
eval_string(s,"Star('test')");

It still runs just fine but it doesn't print anything until after the Matlab function is finished. Is there someway to change this behavior of MATLAB.jl and have Julia print Matlab prompt output as and when it appears ?

thanks a lot !

read/write mat file doc error

in the doc, it says:
mf = MatFile(filename) # opens a MAT file, and returns a handle

it should be updated to
mf = MatFile("test.mat","r") % for reading ....

Only running mf = MatFile("test.mat") returns an error
julia> mf = MatFile("test.mat")
ERROR: no method MatFile(ASCIIString)

when one checks the src, MatFile is defined as a function with two inputs (also visible from methods).
julia> methods(MatFile)
#1 method for generic function "MatFile":

MatFile(filename::ASCIIString,mode::ASCIIString) at ~/.julia/MATLAB/src/matfile.jl:16

myriad ways to segfault

x = mxarray(1.0)
delete(x)
jvariable(x)

calling any MATLAB.jl function on x will segfault.

manually closing window when engine is shown `show_msession()`

ref #79

The only problematic issue here is if the user closes the matlab engine window manually (i.e. clicking the X button) instead of using the hide_msession() function. Because then the pointer to the engine is still attached to a session that does not exist. I'm not sure what is the best way to prevent this from occurring or on how to test if the pointer is still attached to a live engine window; the reason I bring this issue up is that it's possible to segfault julia if you close the window instead of hide_msession().

Tag a new release?

Since the last tag there have been many segfault fixes (i.e. on the latest tag it's still very easy to segfault MATLAB.jl ) and library improvements. I'm now aware of only one possible way to segfault (edit: I'm having a hard time reproducing the segfaults I used be able to generate here) matlab if it's used interactively (see #84)
I think it would make sense to tag a new release soon.

Error "jvalue not defined" - Ubuntu

For some reason an optimization script, that runs perfectly in Windows 10, throws me a "jvalue not defined" error in Ubuntu 17.10 when calling the jvalue() function. All other functions (mxarray(), jarray(),...) work perfectly in Ubuntu, except the jvalue() function.

Does anyone know what might be the problem?

Thanks ;)

Error: The Matlab array must either be a cell array or a double precision matrix

I have compiled lbfgsb on Linux for Matlab. and trying to run the example

with the translation of

using MATLAB

x0  = [-3  -1  -3  -1];   #% The starting point.
lb  = [-10 -10 -10 -10];  ##% Lower bound on the variables.
ub  = [+10 +10 +10 +10];  #% Upper bound on the variables.

mat """
	$x = lbfgsb_mex($x0,$lb,$ub,'computeObjectiveHS038','computeGradientHS038',...
           [],'genericcallback','maxiter',80,'m',4,'factr',1e-12,...
           'pgtol',1e-5);"""

but got the error

 Error using lbfgsb_mex
The Matlab array must either be a cell array or a double precision matrix
 
Error using save
Variable 'jx_lbfgsb_mex_arg_out_1' not found.
 
ERROR: MATLAB.MEngineError("failed to get variable jx_lbfgsb_mex_arg_out_1 from MATLAB session")
Stacktrace:
 [1] get_mvariable(::MATLAB.MSession, ::Symbol) at /home/myname/.julia/v0.6/MATLAB/src/engine.jl:162
 [2] mxcall(::MATLAB.MSession, ::Symbol, ::Int64, ::Array{Int64,1}, ::Vararg{Any,N} where N) at /home/myname/.julia/v0.6/MATLAB/src/engine.jl:291
 [3] mxcall(::Symbol, ::Int64, ::Array{Int64,1}, ::Array{Int64,1}, ::Vararg{Any,N} where N) at /home/myname/.julia/v0.6/MATLAB/src/engine.jl:315

Can anyone shed light on this problem? Simple passing the arrays into matlab and get values out of it are working fine, the error occurs when I try to call the lbfgsb_mex. Note that the other calls i.e. svd, sum in MATLAB work fine.

function callbacks

Is it possible to pass in a Julia function and have matlab call it. Like calling matlab's fzero for example. I don't need fzero, it's just a simple example. I couldn't find a way to do it, but thought I'd ask.

Better MEngineError error messages

Hi!
I'm on Linux version 4.9.0-3-amd64 ([email protected]) (gcc version 6.3.0 20170516 (Debian 6.3.0-18) ) #1 SMP Debian 4.9.30-2+deb9u3 (2017-08-06). I can start MATLAB fine from a terminal, but for some reason MATLAB.jl failed to open a MATLAB engine session:

yakir@debian:~$ julia
               _
   _       _ _(_)_     |  A fresh approach to technical computing
  (_)     | (_) (_)    |  Documentation: https://docs.julialang.org
   _ _   _| |_  __ _   |  Type "?help" for help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.6.0 (2017-06-19 13:05 UTC)
 _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org/ release
|__/                   |  x86_64-pc-linux-gnu

julia> using MATLAB

julia> mat"1+1"
ERROR: MATLAB.MEngineError("failed to open a MATLAB engine session")
Stacktrace:
 [1] MATLAB.MSession(::Int64) at /home/yakir/.julia/v0.6/MATLAB/src/engine.jl:20
 [2] get_default_msession at /home/yakir/.julia/v0.6/MATLAB/src/engine.jl:79 [inlined]
 [3] eval_string(::String) at /home/yakir/.julia/v0.6/MATLAB/src/engine.jl:134

shell> matlab
MATLAB is selecting SOFTWARE OPENGL rendering.
<MATLAB started and I can use it>

This is a fresh install of Debian, so maybe I'm missing something..?

Moving this package to JuliaInterop

To lessen JuliaLang's CI load. @simonster I invited you to that organization, does anyone else actively contribute here? If anyone would like an invite to that organization or otherwise objects to moving this repo, speak up here in the next couple days.

Matlab × symbol does not show correctly in Julia on Windows

Seems to be only an issue on windows.
Look at ZData: [1�0 double]
On linux this shows correctly 1×0

julia> using MATLAB
julia> x = linspace(0,1,10)
julia> eval_string("h=plot($x)")

h =

  Line with properties:

              Color: [0 0.4470 0.7410]
          LineStyle: '-'
          LineWidth: 0.8000
             Marker: 'none'
         MarkerSize: 6
    MarkerFaceColor: 'none'
              XData: [1 2 3 4 5 6 7 8 9 10]
              YData: [0 0.1111 0.2222 0.3333 0.4444 0.5556 0.6667 0.7778 0.8889 1]
              ZData: [1�0 double]

Remove specialized mxarray constructors

I'm trying to add support for complex numbers, and it seems to me that mxarray.jl might be a little simpler without the specialized constructors for matrices and logicals. In my limited benchmarking, it doesn't seem like these are any faster than using mxCreateNumericMatrix for everything. My guess is that they're just syntactic sugar for people writing mex files. @lindahua, is there a reason for these that I haven't found?

Cannot load libeng on OSX 10.8

Hi Dahua,

I think it's great that you made this package as it will be very useful.

However, when I call restart_default_msession() I received the following error:
ERROR: could not load module libeng: dlopen(libeng.dylib, 9): image not found
in load_libeng at /Users/nfoti/src/julia-modules/MATLAB.jl/src/mxbase.jl:42
in MSession at /Users/nfoti/src/julia-modules/MATLAB.jl/src/engine.jl:20
in restart_default_msession at /Users/nfoti/src/julia-modules/MATLAB.jl/src/engine.jl:66
in restart_default_msession at /Users/nfoti/src/julia-modules/MATLAB.jl/src/engine.jl:69

I have verified that the command matlab is on my path and I exported MATLAB_HOME. I'm not sure where libeng is on Linux, but on OSX it appears to live inside the bin/ directory in the Matlab application folder. So maybe the load_libeng function needs to also look there on OSX.

Thanks.

Internal Error: A primary message table for module 77 was already registered with a differing collection of error messages.Severe:

I can't get the tests to pass anymore

INFO: Testing MATLAB
A MATLAB session is open successfully
Internal Error: A primary message table for module 77 was already registered with a differing collection of error messages.Severe:
The program '[2668] C:\Julia\Julia-0.5-latest\bin\julia.exe: Native' has exited with code 1 (0x1).
================================================================================[ ERROR: MATLAB ]=================================================================================

failed process: Process(`'C:\Julia\Julia-0.5-latest\bin\julia' -Cnative '-JC:\Julia\Julia-0.5-latest\lib\julia\sys.dll' --compile=yes --depwarn=yes --check-bounds=yes --code-coverage=none --color=yes --compilecache=yes 'C:\Users\Mus\.julia\v0.5\MATLAB\test\runtests.jl'`, ProcessExited(1)) [1]

==================================================================================================================================================================================ERROR: MATLAB had test errors
 in #test#61(::Bool, ::Function, ::Array{AbstractString,1}) at .\pkg\entry.jl:740
 in (::Base.Pkg.Entry.#kw##test)(::Array{Any,1}, ::Base.Pkg.Entry.#test, ::Array{AbstractString,1}) at .\<missing>:0
 in (::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#test,Tuple{Array{AbstractString,1}}})() at .\pkg\dir.jl:31
 in cd(::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#test,Tuple{Array{AbstractString,1}}}, ::String) at .\file.jl:48
 in #cd#1(::Array{Any,1}, ::Function, ::Function, ::Array{AbstractString,1}, ::Vararg{Array{AbstractString,1},N}) at .\pkg\dir.jl:31
 in (::Base.Pkg.Dir.#kw##cd)(::Array{Any,1}, ::Base.Pkg.Dir.#cd, ::Function, ::Array{AbstractString,1}, ::Vararg{Array{AbstractString,1},N}) at .\<missing>:0
 in #test#3(::Bool, ::Function, ::String, ::Vararg{String,N}) at .\pkg\pkg.jl:258
 in test(::String, ::Vararg{String,N}) at .\pkg\pkg.jl:258

tag patch release

Is attobot installed?

tag a patch release, with fix for MATLAB home path finding for OSX and updates to deprecated methods and syntax

Error in operator parsing

Here's a simple piece of code which fails:

julia> @matlab begin
       a=2*2*2*2;
       end
 a = *(2, 2, 2, 2);
     |
Error: Unexpected MATLAB operator.

Is the parser restricted to operations on two numbers at a time? The above code is fine with explicit parenthesis around every pair of numbers.

Error on Pkg.test() for Julia 0.5

I just installed Julia 0.5 and MATALB.jl. Running Pkg.test("MATLAB") gives me the following error:

ERROR: LoadError: LoadError: LoadError: LoadError: UndefVarError: Uint32 not defined
 in include_from_node1(::String) at ./loading.jl:488 (repeats 2 times)
 in eval(::Module, ::Any) at ./boot.jl:234
 in require(::Symbol) at ./loading.jl:415
 in include_from_node1(::String) at ./loading.jl:488 (repeats 2 times)
 in process_options(::Base.JLOptions) at ./client.jl:262
 in _start() at ./client.jl:318
while loading /home/arora/.julia/v0.5/MATLAB/src/mxarray.jl, in expression starting on line 41
while loading /home/arora/.julia/v0.5/MATLAB/src/MATLAB.jl, in expression starting on line 37
while loading /home/arora/.julia/v0.5/MATLAB/test/engine.jl, in expression starting on line 1
while loading /home/arora/.julia/v0.5/MATLAB/test/runtests.jl, in expression starting on line 1
================================================================================[ ERROR: MATLAB ]================================================================================

failed process: Process(`/home/arora/src/julia_0.5/julia/usr/bin/julia -Cnative -J/home/arora/src/julia_0.5/julia/usr/lib/julia/sys.so --compile=yes --depwarn=yes --check-bounds=yes --code-coverage=none --color=yes --compilecache=yes /home/arora/.julia/v0.5/MATLAB/test/runtests.jl`, ProcessExited(1)) [1]

=================================================================================================================================================================================
ERROR: MATLAB had test errors
 in #test#61(::Bool, ::Function, ::Array{AbstractString,1}) at ./pkg/entry.jl:740
 in (::Base.Pkg.Entry.#kw##test)(::Array{Any,1}, ::Base.Pkg.Entry.#test, ::Array{AbstractString,1}) at ./<missing>:0
 in (::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#test,Tuple{Array{AbstractString,1}}})() at ./pkg/dir.jl:31
 in cd(::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#test,Tuple{Array{AbstractString,1}}}, ::String) at ./file.jl:59
 in #cd#1(::Array{Any,1}, ::Function, ::Function, ::Array{AbstractString,1}, ::Vararg{Array{AbstractString,1},N}) at ./pkg/dir.jl:31
 in (::Base.Pkg.Dir.#kw##cd)(::Array{Any,1}, ::Base.Pkg.Dir.#cd, ::Function, ::Array{AbstractString,1}, ::Vararg{Array{AbstractString,1},N}) at ./<missing>:0
 in #test#3(::Bool, ::Function, ::String, ::Vararg{String,N}) at ./pkg/pkg.jl:258
 in test(::String, ::Vararg{String,N}) at ./pkg/pkg.jl:258

Calling nested functions

Hello:
I can use Matlab function in Julia, but only if the function does not call other functions. In contrast, when calling from Julia from R, I am able to run many functions so long as all are on the same .jl file.

any suggestions would be appreciated

Is it possible to support MATLAB gpuArray?

Since Julia now dosen't have high level supports for GPU computing, MATLAB's GPU operation is attrative. I don't know if it would be difficult to implement such things:

gA=gpuArray(A)
gB=sin(gA)

while gpuArray will call into MATLAB to create a gpuArray and returns a pointer, sin will use MATLAB builtin GPU sin function and returns a pointer.

ERROR: restart_default_msession not defined

I did everything as described in README.me

julia> using MATLAB

julia> restart_default_msession()
ERROR: restart_default_msession not defined

Using OSX 10.8.3
latest julia build
MATLAB package added via Pkg.add("MATLAB")

Thanks mike

tests fail on julia 0.4

Recently upgraded to Julia 0.4. The MATLAB package fails its test.

julia> Pkg.test("MATLAB")
INFO: Testing MATLAB
A MATLAB session is open successfully
ERROR: LoadError: LoadError: MethodError: `mxstruct` has no method matching mxstruct(::Pair{Any,Any}, ::Pair{Any,Any})
Closest candidates are:
  mxstruct{T}(::T)
 in put_variable at /Users/frank/.julia/v0.4/MATLAB/src/matfile.jl:57
 in put_variables at /Users/frank/.julia/v0.4/MATLAB/src/matfile.jl:63
 in write_matfile at /Users/frank/.julia/v0.4/MATLAB/src/matfile.jl:70
 in include at /usr/local/Cellar/julia/HEAD/lib/julia/sys.dylib
 in include_from_node1 at /usr/local/Cellar/julia/HEAD/lib/julia/sys.dylib
 in include at /usr/local/Cellar/julia/HEAD/lib/julia/sys.dylib
 in include_from_node1 at /usr/local/Cellar/julia/HEAD/lib/julia/sys.dylib
 in process_options at /usr/local/Cellar/julia/HEAD/lib/julia/sys.dylib
 in _start at /usr/local/Cellar/julia/HEAD/lib/julia/sys.dylib
while loading /Users/frank/.julia/v0.4/MATLAB/test/matfile.jl, in expression starting on line 18
while loading /Users/frank/.julia/v0.4/MATLAB/test/runtests.jl, in expression starting on line 2
=============================================================================[ ERROR: MATLAB ]=============================================================================

failed process: Process(`/usr/local/Cellar/julia/HEAD/bin/julia --check-bounds=yes --code-coverage=none --color=yes /Users/frank/.julia/v0.4/MATLAB/test/runtests.jl`, ProcessExited(1)) [1]

===========================================================================================================================================================================
ERROR: MATLAB had test errors
 in error at /usr/local/Cellar/julia/HEAD/lib/julia/sys.dylib
 in test at pkg/entry.jl:746
 in anonymous at pkg/dir.jl:31
 in cd at file.jl:22
 in cd at pkg/dir.jl:31
 in test at pkg.jl:71
julia> versioninfo()
Julia Version 0.4.0-dev+6819
Commit 4d72065* (2015-08-18 17:55 UTC)
Platform Info:
  System: Darwin (x86_64-apple-darwin14.4.0)
  CPU: Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz
  WORD_SIZE: 64
  BLAS: libopenblas (DYNAMIC_ARCH NO_AFFINITY Haswell)
  LAPACK: libopenblas
  LIBM: libopenlibm
  LLVM: libLLVM-3.3

pass function name

How the name of the function to be called can be passed? The following fails:

a = "plot"
@MATLAB.mat_str("$a(x, sin(x))")

MATLAB.jl: Error loading MATLAB Module in OSX

Hi am new to Julia and have been trying to use MATLAB.jl. It installed just fine using the Pkg.add("MATLAB") command, but when I type using MATLAB , I get the following error:

ERROR: LoadError: LoadError: MethodError: `min` has no method matching min(::Array{Union(UTF8String,ASCIIString),1})
Closest candidates are:
  min(::Any, ::Any)
  min(::Any, ::Any, ::Any)
  min(::Any, ::Any, ::Any, ::Any...)
 in get_paths at /Users/arora/.julia/v0.4/MATLAB/src/mxbase.jl:20
 in include at /Users/arora/CODES/Julia_source/julia/usr/lib/julia/sys.dylib
 in include_from_node1 at /Users/arora/CODES/Julia_source/julia/usr/lib/julia/sys.dylib
 in include at /Users/arora/CODES/Julia_source/julia/usr/lib/julia/sys.dylib
 in include_from_node1 at /Users/arora/CODES/Julia_source/julia/usr/lib/julia/sys.dylib
 in reload_path at /Users/arora/CODES/Julia_source/julia/usr/lib/julia/sys.dylib
 in _require at /Users/arora/CODES/Julia_source/julia/usr/lib/julia/sys.dylib
 in require at /Users/arora/CODES/Julia_source/julia/usr/lib/julia/sys.dylib
while loading /Users/arora/.julia/v0.4/MATLAB/src/mxbase.jl, in expression starting on line 66
while loading /Users/arora/.julia/v0.4/MATLAB/src/MATLAB.jl, in expression starting on line 34

When I try running commands like restart_default_msession() I get errors lile ERROR: UndefVarError: restart_default_msession not defined

Do you know what could be going wrong here and how can this be fixed ? I am on Julia 0.4. thanks a lot

deprecate duplicate in favor of copy?

I really see no reason for having both.

Right now copy defaults to calling duplicate. Might as well do the Julian thing and just use multiple dispatch over the generic function copy and deprecate duplicate.

Update example with `x = [-10.:0.1:10.]` in the README

This example reproducibly fails:

julia> x = [-10.:0.1:10.]
1-element Array{FloatRange{Float64},1}:
 -10.0:0.1:10.0

julia> y = [-10.:0.1:10.]
1-element Array{FloatRange{Float64},1}:
 -10.0:0.1:10.0

julia> xx, yy = mxcall(:meshgrid, 2, x, y)
Internal Error: A primary message table for module 77 was already registered with a differing collection of error messages.Severe:
The program '[14008] C:\Julia\Julia-0.5-latest\bin\julia.exe: Native' has exited with code 1 (0x1).
Julia Version 0.5.0
Commit 3c9d753 (2016-09-19 18:14 UTC)
Platform Info:
  System: NT (x86_64-w64-mingw32)
  CPU: Intel(R) Core(TM) i7-4510U CPU @ 2.00GHz
  WORD_SIZE: 64
  BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell)
  LAPACK: libopenblas64_
  LIBM: libopenlibm
  LLVM: libLLVM-3.7.1 (ORCJIT, haswell)

Possible rename for consistency

Does it make sense to call this package MATLABCall.jl along the lines of various other packges such as PyCall and JavaCall?

I presume that for Octave, we will need a separate package.

Rename eval_string

eval_string is a pretty generic term to export. I propose we rename it to something more descriptive. Maybe matlab_eval or meval ? Suggestions welcome.

Hide MATLAB Engine Session Window on Windows

Please allow hiding the MATLAB Command Window on Windows. This can be done by using the engSetVisible function.

I would argue that the default should be to not show this window, as I expect the interaction to be done only from within Julia. A use case would be to plot something using MATLAB, which does not require the command window. I also believe that OSX and Linux also do not show this window by default.

Saving figure using export_fig using gcf

I'm attempting to use some old plotting code, and I can't seem to get export_fig to save. Here's a minimal example showing the behavior.

using MATLAB
y = linspace(2., 3., 500)
mat"plot($(y))"
mat"export_fig(gcf,'test.png')"

I can't find test.png anywhere on the system, and neither Julia nor Matlab gives an error.

Trouble loading libmx on Mavericks

I believe it was my update to Mavericks / new Xcode that broke my MATLAB.jl installation. Both my Matlab and my env are the same, but now I get:

ERROR: could not load module /Applications/MATLAB_R2011a.app/bin/maci64/libmx: dlopen(/Applications/MATLAB_R2011a.app/bin/maci64/libmx.dylib, 9): Library not loaded: libtbb.dylib
  Referenced from: /Applications/MATLAB_R2011a.app/bin/maci64/libut.dylib
  Reason: image not found
 in dlopen at c.jl:27
 in load_libmx at /Users/rene/.julia/MATLAB/src/mxbase.jl:77
 in include at boot.jl:238
 in include_from_node1 at loading.jl:114
 in include at boot.jl:238
 in include_from_node1 at loading.jl:114
 in reload_path at loading.jl:140
 in _require at loading.jl:58
 in require at loading.jl:43
at /Users/rene/.julia/MATLAB/src/mxbase.jl:85
at /Users/rene/.julia/MATLAB/src/MATLAB.jl:34

All the mentioned files exist, have the right permissions and even including /Applications/MATLAB_R2011a.app/bin/maci64 in LD_LIBRARY_PATH makes no difference. Trying to add it to DYLD_LIBRARY_PATH crashes Julia during start (before using MATLAB).

(Un-)Setting MATLAB_HOME makes no difference. (Also there is only 1 Matlab installed)

Running Julia Version 0.2.0+26 (2013-11-18 19:08 UTC) and current MATLAB.jl cloned from git URL.

I think the only difference between the last-working state and now is the installation of Mavericks / Xcode updates.

Does anybody see the same behavior? Any hints very much appreciated!

Module does not load with recent Julia

Some recent updates in Julia used to show warnings with MATLAB.jl, but it does not work at all with the most recent builds (commit 876e0d3):

julia> using MATLAB
ERROR: `min` has no method matching min(::Array{Union(UTF8String,ASCIIString),1})
 in get_paths at /Users/jfsantos/.julia/v0.3/MATLAB/src/mxbase.jl:20
 in include at ./boot.jl:245
 in include_from_node1 at ./loading.jl:128
 in include at ./boot.jl:245
 in include_from_node1 at ./loading.jl:128
 in reload_path at loading.jl:152
 in _require at loading.jl:67
 in require at loading.jl:51
while loading /Users/jfsantos/.julia/v0.3/MATLAB/src/mxbase.jl, in expression starting on line 66
while loading /Users/jfsantos/.julia/v0.3/MATLAB/src/MATLAB.jl, in expression starting on line 34

min now only works between two values, and this is operating on an Array, but I don't know if it is just the case of switching min by minimum everywhere.

Failed to open a MATLAB engine session on Windows

Hello,
When calling restart_default_msession(), I get the following error on Windows:
ERROR: MEngineError("Failed to open a MATLAB engine session.")
in MSession at C:\Users\CAPADUB.julia\MATLAB\src\engine.jl:26

I'm using Matlab R2014a 64 bits. I tried setting the env variable MATLAB_HOME to no avail.

Any idea of what might be going on? I can start Matlab from a normal Windows command prompt.

Warning has(d,k)

WARNING: has(s::Set,x) is deprecated, use contains(s,x) instead.
in write_mstatement at /Users/mike/.julia/MATLAB/src/mstatements.jl:52

Could you please fix this?

Thanks,

Mike

Question: Changing m-file has no effect.

Hi,

I am doing some tests and have an m-file test.m. I am calling this with

mat"""
result = test();
"""
@mget result
println(result)

Everything works great. My result is extracted from Matlab into Julia and I can print it to the REPL, BUT if I change the m-file, the output is unchanged.

I guess this illustrates a misunderstanding on my part? I thought mat"..." simply called my Matlab function, but if that were the case, changes to test.m would be reflected in Julia, but changes are not being reflected. Why is that? Is there some way to have changes to the m-file reflected in Julia?

Start Matlab session with -singleCompThread ?

I wanted to ask if there is a way to start a Matlab session with Multithreading turned off, so to achieve the same like starting matlab with the -singleCompThread command line option?

Invalid MATLAB Path

Whenever I type
Using Matlab
I get the following error message
1

However when I check my user environment variables, using versioninfo(true)
2
and checking my root in MATLAB,
3
Is there a reason why it can't read my MATLAB root?

Installing a new version of MATLAB

I would like to share my experience with installing a new version of MATLAB (Ubuntu 16.04). From what I understood, MATLAB path is determined by which matlab during precompilation, which returns a path to a particular version. If a new version of MATLAB is installed, it will not be automatically picked up if the precompiled module already exists, unless you force recompilation with Base.compilecache("MATLAB"). I am suggesting that either this should be documented, or perhaps a symlink to MATLAB installation could be used instead.

Tag a new version?

The last tag is really old and won't work anymore because of an error looking for UInt32.

Pressing Control-C breaks MATLAB engine

After pressing control-C at a blank prompt with a MATLAB engine session open, MATLAB is still running, but if I attempt to run a MATLAB command, I get:

ERROR: MEngineError("Invalid engine session.")
 in eval_string at /Users/simon/.julia/MATLAB/src/engine.jl:102
 in eval_string at /Users/simon/.julia/MATLAB/src/engine.jl:111

and then I need to restart Julia before anything MATLAB-related works again. I think this used to work in previous versions of Julia, although I'm not positive.

Problems with dynamic libraries with Matlab in osx

Hi, I was getting an error relating to not being able to find the dynamic libraries in matlab when I issued the using MATLAB command.

I think it was to do with the fact that although the correct lopen command was being issued for libmx.dylib (with the full library path being specified), when libmx was trying to open libtbb.dylib it was using just the "raw" name. Since we weren't in the Matlab.app per se it was failing to find it.

My (inelegant) work around was to edit the julia script (/Applications/julia.app/Contents/Resources/script) to include the correct DYLD_FALLBACK_LIBRARY_PATH, which works.

(Using DYLD_LIBRARY_PATH causes Julia to stop working).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.