Connecting Matlab and Pure Data via TCP/IP

Eventually, one might want to establish a comunication between Matlab and PD to have the best of both worlds. We’ll show how to do this using jtcp in the following. Download it and put it somewhere in the Matlab path.

Open the following PD patch (right click on the image and ‘save target as’ to download the patch).

tcp_to_matlab

Connect Matlab to netreceive:

>> jtcp_obj_netreceive = jtcp( ‘request’, ‘127.0.0.1’, 2101, ‘serialize’, false );

127.0.0.1 is the localhost, 2101 is the port. Prepare Matlab for the connection with netsend:

>> jtcp_obj_netsend = jtcp( ‘accept’, 2100, ‘serialize’, false, ‘timeout’, 10000 );

Now you have 10 sec to click the message ‘connect 127.0.0.1 2100’ in PD, otherwise jtcp will complain. Note that you have to use different ports for sending an receiving (2101 vs. 2100) in this example. Which ports you are actually using is your choice.

Click ‘send 1’ in PD and execute the following commands to read the message in Matlab:

>> message_from_pd = jtcp( ‘read’, jtcp_obj_netsend );
>> disp( message_from_pd );
49   59   10

Note the ending characters:

>> disp( char( message_from_pd ) );
>> 1;
>> disp( str2num( char( message_from_pd( 1 : end – 2 ) ) ) );
1

Click the message ‘send Hello Matlab!’ in PD;

Execute again the following command in Matlab.

>> message_from_pd = jtcp( ‘read’, jtcp_obj_netsend );
>> disp( char( message_from_pd( 1 : end – 2 ) ) );
Hello Matlab!

Now that we got this sorted out, we know what we have to send to PD to achieve the desired result.

To send the number ‘1’ to PD type

>> jtcp( ‘write’, jtcp_obj_netreceive, [ int8( num2str( 1 ) ) 59   10 ] );

Here, we convert the number ‘1’ to a character, which in turn we convert to a keycode. Note the keycodes ’59’ and ’10’ for the ending characters. You should now see the message ‘Message from Matlab: 1’ in the PD message window.

To send a string to PD, type

>> jtcp( ‘write’, jtcp_obj_netreceive, [ int8( ‘Hello PD!’ ) 59   10 ] );

in the Matlab command window. Note the keycodes ’59’ and ’10’ for the ending characters.

You should now see the message ‘Message from Matlab: Hello PD!’ in the PD message window.

Finally, to disconnect type

>> jtcp( ‘close’, jtcp_obj_netreceive );
>> jtcp( ‘close’, jtcp_obj_netsend    );

and click the ‘disconnect’ message in PD.