• No results found

Blogs Mathworks Com

N/A
N/A
Protected

Academic year: 2021

Share "Blogs Mathworks Com"

Copied!
5
0
0

Loading.... (view fulltext now)

Full text

(1)

Search: Blogs

File Exchange Answers Newsgroup Link Exchange Blogs Trendy Cody Contest MathWorks.com

Blogs

Subscribe

Loren on the Art of MATLAB

All MathWorks Blogs

expand all 55 31 6 42 60 1 JUL Natural Neighbor - A Superb Interpolation Method

24 JUN How Do You Modify the Background of an Image? 18 JUN Getting Started with Kaggle Data Science Competitions 11 JUN Advice for Making Prettier Plots 22 MAY Including External Code in Published Document Categories Best Practice Robustness Big Data Common Errors Less Used Functionality

more

Recent Comments

Duncan on Getting Started with Kaggle Data Science Competitions Toshi Takeuchi on Getting Started with Kaggle Data Science Competitions Brett Shoelson on How Do You Modify the Background of an Image? Ilyas on Getting Started with Kaggle Data Science Competitions michael on How Do You Modify the Background of an Image?

Recent Posts Archive

Transferring Data Between Two Computers Using MATLAB

Posted by Loren Shure, May 27, 2011

This week's guest bloggers Ankit Desai and Vinod Cherian work on various aspects of using MATLAB to control instruments, make measurements with hardware, retrieve data from instruments, and do custom analysis in MATLAB. In this post they talk about transferring data between two separate MATLAB sessions using TCP/IP client-servers.

There are many cases where an operation needs to be performed in one MATLAB session and the data needs to be transferred to a different machine for further analysis and visualization in MATLAB. Many of you have asked about transferring MATLAB arrays between two MATLAB sessions on MATLAB Answers, the MATLAB newsgroup, and through technical support.

To show you an example of how this may be accomplished we've written an example that transfers the array of data required to create an L-shaped membrane. The script uses the tcpip function in Instrument Control Toolbox. Specifically it uses the new NetworkRole property, which is a new property of tcpip objects in R2011a.

The example consists of two parts:

A MATLAB session on a server that needs to transfer its data out

A second MATLAB session on a client computer that retrieves and plots the data Contents

Setting Up a MATLAB TCPIP Server Session Setting Up the MATLAB Client Session Closing Notes

Setting Up a MATLAB TCPIP Server Session

The MATLAB server session creates a data set to be transferred out, opens a TCP/IP server socket and waits for the client to connect to it. When the connection is established, the data is written out to the socket.

Prepare the data we want to send over to the client MATLAB session. In this case our data is created by a call to the membrane function.

data = membrane(1);

Let us list details of the data set we want to transfer. We will use this information later to set up some parameters on the server socket and in the client.

s = whos('data') s = name: 'data' size: [31 31] bytes: 7688 class: 'double' global: 0 sparse: 0 complex: 0 nesting: [1x1 struct] persistent: 0

Get the dimensions of the data array we will be transferring.

s.size

ans = 31 31

Get the number of bytes of data we will be transferring.

s.bytes

|

< What a Difference It Makes! Introducing Type Safe APIs with... >

(2)

ans = 7688

Start a TCP/IP server socket in MATLAB. By setting the IP address to '0.0.0.0' the server socket will accept connections on the specified port (arbitrarily chosen to be 55000 in our case) from any IP address. You can restrict the TCP/IP server socket to only accept incoming connections from a specific IP address by explicitly specifying the IP address. Note the new property NetworkRole.

tcpipServer = tcpip('0.0.0.0',55000,'NetworkRole','Server');

Set the OutputBufferSize property to a value large enough to hold the data. This is the first place where we use the output of the whos function, specifically the value of s.bytes.

set(tcpipServer,'OutputBufferSize',s.bytes);

Open the server socket and wait indefinitely for a connection. This line will cause MATLAB to wait until an incoming connection is established.

fopen(tcpipServer);

Since the MATLAB server code is running in a separate MATLAB session than the client, you may notice the Busy status next to the MATLAB Start Button in the server session until the following commands have been executed. You may stop the MATLAB server socket creation and break out of this busy state by using the Control-C key combination to close the server socket. Note that once you close the server socket clients will no longer be able to connect to it until it has been re-opened.

Once the connection is made by the client, write the data out and close the server.

fwrite(tcpipServer,data(:),'double'); fclose(tcpipServer);

Setting Up the MATLAB Client Session

The MATLAB server session is running on a computer with a known IP address or hostname. In our case, this is the address '127.0.0.1'. The second MATLAB session that acts as the client application creates a TCP/IP client, connects to the server and retrieves the data. Once retrieved, the data will be visualized in the client session.

Create a MATLAB client connection to our MATLAB server socket. Note the value of the NetworkRole property on the client. Also note that the port number of the client matches that selected for the server.

tcpipClient = tcpip('127.0.0.1',55000,'NetworkRole','Client')

TCPIP Object : TCPIP-127.0.0.1 Communication Settings RemotePort: 55000 RemoteHost: 127.0.0.1 Terminator: 'LF' NetworkRole: client Communication State Status: closed RecordStatus: off Read/Write State TransferStatus: idle BytesAvailable: 0 ValuesReceived: 0 ValuesSent: 0

Set the InputBufferSize property so we have sufficient room to hold the data that will be sent to us by the server. The number 7688 is the number of bytes in the data array. For more general purpose code, you can parametrize this code by using the value in s.bytes instead of the hard-coded value of 7688.

set(tcpipClient,'InputBufferSize',7688);

I will define a long value for the Timeout; the waiting time for any read or write operation to complete. Adjust this value to ensure that any data that is being transferred to the client will be read back within the selected timeout.

set(tcpipClient,'Timeout',30);

Open a TCPIP connection to the server.

(3)

1 of 11

2 of 11

Oldest to Newest Read the data that is being written out on the server. Note that the data types need to be matched up on the client and server. The number of double values to be read back from the server socket is 961. For more general purpose code, you may parametrize the second argument using prod(s.size), for example.

rawData = fread(tcpipClient,961,'double');

Close the connection to the server once we've retrieved the data.

fclose(tcpipClient);

Reshape the data array and plot it. You can parametrize this by specifying s.size as the input to reshape instead of the hard-coded array size (31x31).

reshapedData = reshape(rawData,31,31); surf(reshapedData);

Closing Notes

Note that this functionality is meant to be used behind a firewall or on a private network, and should be used in accordance with the license agreement as it relates to your particular license option and activation type. For more information on using MATLAB TCP/IP server sockets refer to the documentation.

We could see a number of uses of this functionality; an example being using MATLAB on an instrument used to gather data. Using TCP/IP server sockets in MATLAB it is now possible to transfer the data out, without the need for files, to a remote computer for further analysis and visualization in MATLAB.

How do you see this functionality being used? Post your responses here.

Get the MATLAB code Published with MATLAB® 7.12

11 Comments

Daniel Armyr replied on May 27th, 2011 2:41 pm UTC :

And for those who do not have the Instrument Control Toolbox, an excellent alternative to send data over networks is http://www.mathworks.com/matlabcentral/fileexchange/345-tcpudpip-toolbox-2-0-6

It is not rock-solid for maintaining connections over days and days, but for every-day use it is fast, simple and well-documented.

I have used it to build my own alternative to the Parallell Processing toolbox (One Matlab spawns other sessions and then hands out tasks via network communication) among other things.

Ian replied on May 29th, 2011 3:27 pm UTC :

Thanks, didn’t know about the new NetworkRole functionality. I’va also been using PNet for TCP/UDP communication

Category: How To 0

|

< What a Difference It Makes! Introducing Type Safe APIs with... >

(4)

3 of 11 4 of 11 5 of 11 6 of 11 7 of 11 8 of 11 9 of 11

between Matlab instances so far.

One critical block, and something Mathworks could fix easily – what happens when I want to send matlab objects, there is no way to serialize objects except save to disk, read bytes from disk and send them; write to disk on the server and then read the resultant mat file. This is very slow!!!

I also think the TCP communication should be part of Matlab core, this is useful for so much more than controlling external instruments (as your post shows)!

ali replied on November 1st, 2011 8:23 am UTC :

hi….i have some questions that this passage coulden`t helep me… so…

let`s answer me…

in the case ofconnection to matlab by some diffrenet application … i need to make that imagin real…

I`ve rote a programm…that need to the mass calculating so I realy haveto work by matlab… i can not connetct this to any vay…

clear the way for me show me how I can connect this to each other…..!

Ankit replied on November 2nd, 2011 7:58 pm UTC : Ali,

If I understand your question correctly, you are trying to connect MATLAB to some other application. You should be able to do it in a manner very similar to the steps listed in the example above.

You need to know the following things before setting up the connection: 1. Is MATLAB a server or the client?

2. The IP address and communication port for the other application

Depending on the information above, you should be able to tweak the example above for your use. In case of MATLAB being the server:

tcpipServer = tcpip('0.0.0.0',,'NetworkRole','Server');

In case of MATLAB being the client:

tcpipServer = tcpip('',,'NetworkRole','Client');

The MATLAB Central File Exchange entry (http://www.mathworks.com/matlabcentral/fileexchange/27290-collect-and-plot-data-from-a-tcpip-server-in-real-time) should help you in understanding the later configuration.

Hope this helps.

Bakhtiar replied on January 9th, 2012 2:54 pm UTC : Hi;

I’m using the Instrument control toolboax with MATLAB R2009b, the “NetworkRole” property does not exist, how can start the tcpip on the server. I want to have a TCPIP senssion between to MATLAB sessions.

Regards

Ankit replied on January 11th, 2012 3:40 pm UTC : Bakhtiar,

The ‘NetworkRole’ property for TCPIP object was introduced only in release R2011a. TCPIP object as a server is not supported in R2009b.

Regards, -Ankit

Peter Sobol replied on January 22nd, 2012 8:47 pm UTC :

Is there anyway to get a server socket to timeout if it doesn’t receive a connection within a period of time?

Peter replied on January 23rd, 2012 3:35 pm UTC :

Is there a way to set a timeout for a the server connection so that if it doesn’t receive a connection within a certain time the process can continue? Right now once fopen(tcpipServer); is issued the only way out is ctl-C.

Ankit replied on January 25th, 2012 8:46 pm UTC : Hi Peter,

Unfortunately there is no way for fopen(tcpipServer) to timeout. Currently the only way out is to use Ctl+C. However, I will enter this enhancement request in our internal database for future consideration. Thanks,

(5)

© 1994-2015 The MathWorks, Inc. Site Help Patents Trademarks Privacy Policy Preventing Piracy Terms of Use

Featured MathWorks.com Topics: New Products Support Documentation Training Webinars Newsletters MATLAB Trials Careers 10 of 11

11 of 11

Joanna Castellano replied on January 31st, 2012 4:31 pm UTC :

I would like to expand on the idea of communication between Matlab and other applications. (As referred to in response #4) Instead of transferring data between applications, I would like to have tcl tell Matlab to run a script. Is that possible? Thank you.

Val Schmidt replied on February 7th, 2012 9:17 pm UTC :

I agree with another poster – that tcp/ip functionality should be built into MATLAB core.

Moreover, I think the ability to do this at this low level is great, but why must it always be so hard? Here’s the level at which I think it should work:

One should be able to list all instances of MATLAB running on the local network (or specify an IP address for a specific computer). Then one should be able to select an instance and “send” it any MATLAB

variable/matrix/object/structure/cellarray/etc. The receiver should be able to automatically accept objects sent from known senders or should be prompted for acceptance. All the details regarding the connection should be completely transparent. It should just work.

Another feature should include the ability to share a workspace between two instances of MATLAB. In that way, users collaborating on a data set could work simultaneously and see each other’s results. One could even select which plots should show up on the other person’s workstation.

My 2 cents. Val

References

Related documents

○ If BP elevated, think primary aldosteronism, Cushing’s, renal artery stenosis, ○ If BP normal, think hypomagnesemia, severe hypoK, Bartter’s, NaHCO3,

I problematize three family images associated with the design and implementation of housing projects: the bureaucratic family, envisaged by policymakers as conflating with a model

Summary In a phase 2 trial of 222 postmenopausal women with osteoporosis aged 55 to 85 years randomized to one of three different doses of abaloparatide-SC, subcutaneous

The encryption operation for PBES2 consists of the following steps, which encrypt a message M under a password P to produce a ciphertext C, applying a

Accelerometer, survey and Geographic Information Systems (GIS) data for 6,181 participants from 12 cities in 8 countries (Belgium, Brazil, Czech Republic, Denmark, Mexico,

Acknowledging the lack of empirical research on design rights, our paper wishes to investigate the risk of piracy and the perceptions of the registered and unregistered design

In this PhD thesis new organic NIR materials (both π-conjugated polymers and small molecules) based on α,β-unsubstituted meso-positioning thienyl BODIPY have been