Passing strings from Matlab to Julia and back using Sockets

I needed a simple communication channel between Matlab and Julia. Maybe this will help someone, so here’s the code (spoiler alert, everything is an ascii character):

## Matlab to Julia TCPIP communication example

# Julia - server side
using Sockets 

server = listen(ip"127.0.0.1", 2001)
sock = accept(server)
x=0

@async while true
	global x = readline(sock)
	println(x)
end
# after receiving a message
numeric = parse.(Float64, split(x)) # where x is "-1.2158      1.5908     0.52648", vector coverted by Matlab to string

% Matlab - client side
client = tcpip('127.0.0.1', 2001, 'NetworkRole', 'client');
client.OutputBufferSize = 1024
client.InputBufferSize = 1024
fopen(client)

fprintf(client, '%s', '1,2,2,3\n') %this is sent as string; \n is mandatory
x=randn(1,3);
y=num2str(x);
y=[y, '\n'];
fprintf(client, '%s', y)

fclose(client)

######################################################################

## Julia to Matlab communication example
% Matlab - server side
server = tcpip('127.0.0.1', 2000, 'NetworkRole', 'server');
fopen(server);

% after receiving a message
data = fread(server, server.BytesAvailable) % ascii characters corrsponding to [1,2,4]\n

fclose(server)

# Julia - client side
using Sockets 

client = connect(2000)

println(client,[1,2,4]) #this is sent as string

3 Likes

Just in case, if you do not know, you can call MATLAB from Juila with:

This is similar to PyCall (and pyjulia based on it to call in the other direction). I only know of that way to call in that to Julia, not the other way around. I suppose something similar to pyjulia could be built on it, or some way to do the same with hand-written callbacks.

There’s also the possibility to use .m files and pass back and forth. I’m also doing similar to above, and calling Octave, a MATLAB clone.

1 Like

Thank you for the link! In my case I needed to call Julia from Matlab. Since I mostly needed to pass strings, the socket approach was straightforward and an opportunity for me to learn something new. Writing to files is indeed a viable solution since I don’t care that much about latency.

I found https://github.com/juliamatlab/julia-matlab-shuttle which looks interesting but it’s not maintained. I might try to revive it. Not sure how it works though…

You can also try this package: https://github.com/NBoulle/Mex.jl

Note that it is currently not super robust and sometimes crashes MATLAB when an error happens on the Julia side. I’ve been using it though, and it works fine (again, as long as no error occurs in Julia).

2 Likes

Thanks for the suggestion! I tried it and it worked! The only problem I encountered was the Julia default installation path :upside_down_face: which has a space: C:\Julia 1.5.0, causing the path to be truncated to C:\Julia during compilation.

1 Like