Communications between two MatLabs (2): over socket

October 17th, 2016

Aaron Piccirilli

Aaron Piccirilli

After the previous blog post Communications between two MatLabs (1) over file, Aaron Piccirilli in our lab suggested a more efficient way to communicate between two matlabs, i.e. over socket. Below is the source code provided by Aaron:

udpSocket = udp('', 'LocalPort', 2121, 'RemotePort', 2122);
udpCleaner = onCleanup(@() fclose(udpSocket));
for ii = 1:100
    fprintf(udpSocket, '%d%f', [ii ii/100]);
    disp(['Sending ' num2str(ii)]);
udpSocket = udp('', 'LocalPort', 2122, 'RemotePort', 2121);
udpCleaner = onCleanup(@() fclose(udpSocket));
    if udpSocket.BytesAvailable
        ii = fscanf(udpSocket, '%d%f');
        disp(['Received' num2str(ii(1)) '-' num2str(ii(2))])

More words from Aaron:

I also wrote a couple of quick tests to compare timing by having each method pass 10,000 random integers as quickly as they could. Using UDP is over four times faster on my work machine, and would be sufficient to keep up with sampling rates up to about 900 Hz, whereas the file-based transfer became too slow at about 200 Hz.

Obviously these rates and timings are going to be system and data-dependent, but the UDP implementation is about the same amount of code. It has some added benefits, too. First is what I mentioned before - that this allows you to communicate between different languages. Second, though, is what might be more important: buffer management. If your data source is sending data faster than you can process it, even for just a moment, the UDP method handles that gracefully with a buffer. To get the same functionality with the file method you have to write your own buffer maintenance - not too tricky, but adds another layer of complexity and probably won’t be as efficient.

I did a similar timing test passing 40 floats each time (say for 20 channels of NIRS data) instead of a single integer and the timing did not really change on my machine.

I also tested the above scripts, and they work beautifully! I definitely recommend this method over the ‘file’ method. One thing to note: when you Ctrl-C to quit the program, remember to close the socket (fclose(udpSocket)) AND clean the variables (udpSocket, udpCleaner); otherwise you will run into the “Unsuccessful open: Unrecognized Windows Sockets error: 0: Cannot bind” error.

Note from Aaron:

One note: the onCleanup function/object is designed as a callback of sorts: no matter how the function exits (normally, error, crash, Ctrl-C), when the onCleanup object is automatically then destroyed, its anonymous function should run. Thus, the UDP connection should be closed no matter how you exit the function. This won’t work for a script, though, or if you were just running the code on its own in a command window, as the onCleanup object wouldn’t be automatically destroyed. I would just exclude that line completely if you weren’t running it as a function.

Author: Xu Cui Categories: matlab, programming Tags:

Communications between two MatLabs (1) over file

October 3rd, 2016

Ref to: Communications between two MatLabs (2): over socket

It’s common that two MatLab programs needs to communicate. For instance, one program is collecting the brain imaging data but not display them, and the other program is to display the data. (Another case is at Sometimes it is not practical to merge the two program together (e.g. to keep the code clean). In this case we can run two MatLabs simultaneously. One keeps saving the data to a file, and the other keep reading the file.

Here I played with such a setup, and find they communicate well with small delay (small enough for hemodynamic responses). Check out the video below:


for ii=1:100
    disp(['write ' num2str(ii)])

last_ii = 0;
        load data
        if(ii ~= last_ii)
            disp(['get data. i=' num2str(ii)])
        last_ii = ii;

Caveat: writing/reading to/from disc is slow. So if your experiment requires real time communication without any delay (say <1ms), this method may not work. Also, the amount of data to write/read each time should be very small, and the frequency of write should be small too. The file needs to locate in your local hard drive instead of a network drive.

———- Comments ———–
Paul Mazaika from Stanford:
Cool piece of code! There may be a way to do this with one umbrella Matlab program that calls both components as subroutines. The potential advantage is that one program will keep memory in cache, not at disk, which can support rapidly updating information. For high speeds, it may be better to only occasionally update the graphical display, which otherwise may be a processing bottleneck.

Aaron Piccirilli from Stanford:
There is, sort’ve! I think Xu’s little nugget is probably best choice for many applications, but if speed is an especially big concern then there are a couple of options that I’ve come across that will maintain some sort of shared memory.

Perhaps the easiest is to use sockets to communicate data, via UDP or TCP/IP, just like you use over the internet, but locally. You write some data to a socket in one program, and read it from that same socket in another program. This keeps all of your data in memory as opposed to writing it to disk, but there is definitely some overhead for housekeeping and to move the data from one program’s memory into the operating system’s memory then back into the other program’s memory. An added bonus here: you can communicate between different languages. If you have a logging function written in Python and a visualization program in MATLAB, they can pretty easily communicate with each other via sockets.

MATLAB doesn’t have explicit parallel computing built-in like many other languages, sadly, but we all have access here to the Parallel Computing Toolbox, which is another option for some more heavy-duty parallel processing where you have a problem you can easily distribute to multiple workers.

Finally, true shared memory might be more trouble than it’s worth for most applications, as you then have to deal with potential race conditions of accessing the same resource at the same time.


More on this topic: Please continue to read Communications between two MatLabs (2): over socket

Author: Xu Cui Categories: brain, matlab, nirs, programming Tags:

A part-time position promoting Stork

September 2nd, 2016



We are looking for a passionate team member to join us in promoting Stork in the region of North America and Europe. Stork is research tool which notifies researchers new publications and grants based on their own keywords. It’s straightforward and easy to use.


  1. Major in biology related fields
  2. Minimum degree: BS
  3. Willing to learn
  4. This is a part-time job. Location does not matter. Working hours is flexible.

If you are interested, please contact us at with your resume.

Author: Xu Cui Categories: stork Tags:

Postdoc position available in our lab at Stanford

August 24th, 2016

Our lab is hiring a “sports neuroscience postdoc”. See the detail below. If you are interested, please contact Reiko Riley (mentioning that you heard about this position from Xu’s blog):


A sports neuroscience postdoctoral fellowship is available in the Division of Interdisciplinary Brain Sciences (CIBSR), Stanford University School of Medicine Department of Psychiatry, to study the neurobiology of cycling-based exercise using functional near-infrared spectroscopy (fNIRS).

The postdoctoral fellow will have the opportunity to develop and contribute to an innovative project in sports neuroscience, investigating the contribution of cycling exercise to brain function and cognition. The fellow will be involved in the development of a cycling exercise program protocol, brain-computer interfaces and computational methods to process and analyze data across multiple scientific levels. Successful candidates will have the opportunity to investigate whether cycling exercise can be used as a tool to improve attention in individuals with cognitive dysfunction such as ADHD, and the utility and feasibility of biometric tools to complement fNIRS. The trainee accepted into the program will work collaboratively with a program mentor (or mentors), who will help to define, enhance and monitor the trainee’s research program and career trajectory. The CIBSR team dedicated to fNIRS research includes Drs. Allan Reiss (CIBSR Director, Clinical Neuroscience and Neuropsychiatry), Hadi Hosseini and Ning Liu (Bioengineering), Jennifer Bruno (Developmental Neuropsychology), Manish Saggar and Xu Cui (Computational Neuroscience), and Joseph Baker (Experimental Psychology). The training program also offers didactic courses and activities (e.g., journal club and career lunches) as well as opportunities for diverse industry and academic collaborations to promote professional development. The Stanford School of Medicine is ranked #2 in the U.S. News & World Report rankings, with the highest NIH-funding-per-faculty ratio in the United States.

Requirements: M.D. or Ph.D. in neuroscience, cognitive science, computer science, biomedical engineering, biostatistics, physics, psychology, kinesiology or a related/relevant field. Applicants should have (or anticipate having) a Ph.D. and research background in computational neuroscience, cognitive neuroscience and/or functional brain imaging. Applicants with experience conducting Near Infrared Spectroscopy studies and data analysis procedures will receive preference. Experience in sports neuroscience is also a plus. Responsibilities will include manuscript preparation and grant preparation. The successful applicant will have well-developed problem solving skills, be able to manage several projects simultaneously, lead and mentor students and research assistants, have excellent computing as well as verbal and written English skills, and an aptitude for writing manuscripts and giving scientific presentations.

Application Materials Required - submit via email to our training coordinator Reiko Riley (

Current CV
Post Doctoral Application (link:
Research Statement (description on page 2 of the application form below)
2 - 3 Letters of Reference

Official announcement link:

Author: Xu Cui Categories: life Tags:


August 11th, 2016



1. 我的导师是否有经费?
2. 我在寻找博后的职位;我未来的老板是否有足够的经费支持我?
3. 有多少经费拨给了我的研究领域(比如NIRS)?谁得到了这些经费?他们将用这些经费做什么?



Stork 就是这样一个工具。

我在Stork里输入如下关键字,“pearl chiu”(我之前同事的名字)以及“NIRS brain”(我的研究领域)。以下是Stork发给我的邮件:

Stork notifies me of awarded grants


有了Stork提供的信息,我了解了在我的研究领域,谁得到了经费以及他们打算用这笔经费做什么研究。实际上邮件里的第三个基金是拨给我的同事Manish, 用于他进行利用NIRS对静息状态下的脑回路的研究。我还看到Pearl得到了很大一笔经费,所以我给她发送了一封祝贺邮件。与Stork的另一个功能论文提醒比起来,经费提醒让我更早的对自己研究领域的趋势了如指掌。得到经费支持的研究,通常需要几年之后才有相关论文发表出来。


Author: Xu Cui Categories: brain, programming, web, writing Tags:

A mistake in my False discovery rate (FDR) correction script

August 8th, 2016

I have posted an FDR script at I noticed that there is a small bug. In rare cases, this bug will cause the most significant voxel to be classified as ‘non-significant’ while other voxels are ’significant’.

Consider the following example:

p = [0.8147 0.9058 0.0030 0.9134 0.6324 0.0029 0.2785 0.5469 0.9575 0.9649 0.1576 0.9706 0.9572 0.4854 0.8003 0.1419 0.4218 0.9157];

The previous script will classify p(3) as significant but p(6) as non-significant.

Here is the updated version of the script:

function y = fdr0(p, q)
% y = fdr0(p, q)
% to calculate whether a pvalue survive FDR corrected q
% p: an array of p values. (e.g. p values for each channel)
% q: desired FDR threshold (typically 0.05)
% y: an array of the same size with p with only two possible values. 0
% means this position (channel) does not survive the threshold, 1 mean it
% survives
% Ref:
% Genovese et al. (2002). Thresholding statistical maps in functional
% neuroimaging using the false discovery rate. Neuroimage, 15:722-786.
% Example:
%   y = fdr0(rand(10,1),0.5);
% Xu Cui
% 2016/3/14

pvalue = p;
y = 0 * p;

[sortedpvalue, sortedposition] = sort(pvalue);
v = length(sortedposition);
for ii=1:v
    if q*ii/v >= sortedpvalue(ii)
        y(sortedposition(1:ii)) = 1;

Author: Xu Cui Categories: brain, matlab, nirs, programming Tags:

Remote Desktops

July 25th, 2016

I have quite a few devices now: one computer (PC) at Stanford, one (PC) at home, one Macbook Pro laptop, one iPhone and iPad. I am sometimes at work, sometime home, sometimes travelling, sometimes meeting people. One thing I always want to achieve is to be able to access the computers from anywhere.

I did some research and Google’s Chrome Remote Desktop is a good choice. It is also free. It is a plugin of Chrome browser. For iphone/iPad, Google also offers an app. I installed Chrome Remote Desktop on all my devices, and now I can access any computer from any other devices.

remote desktop

remote desktop

This is what I hoped for - a full connection. But at this particular moment I can’t use the home computer to remote others. I got the famous “some required components are missing” error and don’t know how to solve it. If you know a solution, please let me know.

Author: Xu Cui Categories: life Tags:

3 monitors

July 18th, 2016

To be more “productive”, I recently upgraded my work space. I used to have 2 monitors side by side. Both of them are View Sonic but they are of different size and one is old. So I purchased two monitors (Dell U2415). Together with one original View Sonic monitor, now I get 3 monitors on my desk.

3 monitors

3 monitors

The left one is the original view sonic one with resolution 1920 x 1080. I make it vertical because I write a lot of codes and a vertical placement allows me see more lines of codes at the same time. So this monitor is almost dedicated to writing codes.

The right two are Dell U2415 with resolution 1920 x 1200. According to some people, “Dell UltraSharp series is a gold standard in excellence which programmers have used and loved for years”. I myself do love it a lot. These monitors have a very thin bezel, which is ideal for side-by-side placement. I use the middle screen for the current job (Excel, browsing etc), and the right screen for supportive function (e.g. wechat, FileZilla, QQ, windows explorer etc).

Of course, to make the 3 monitor setup possible, I need a trip-monitor stand. The one I use is SIIG 13″-27″ Articulated Freestanding Triple Monitor Desk Stand. It does an OK job. One of the reason I chose it because it does not need a grommet. I am using varidesk and there is not much space under the table.

Overall, I like the 3 monitors a lot. I do feel I am more “productive” :)

Author: Xu Cui Categories: life, technology Tags:

MatLab tip, save data in compressed mode

June 29th, 2016

I have a mat file which is 100+M in size. It would be fine normally but since I was trying to upload it to github, it was rejected due to its big size. Fortunately there is a way to reduce the size: save it again in the compressed mode.

After I load the file, I save the variable again using the following command:

save filename variablename -v7

The parameter -v7 is the key. How does the compression perform? Originally the file (render_ch2bet) size is 103M, with -v7 parameter the file is 40.9M (render_ch2bet_compressed). By comparison, if we compress the original file using a third party program, we got ~40M ( If we use the -v7 option, not only we get a much smaller file and save a lot of space, we can also load it directly in MatLab.

Compressed MAT file

Author: Xu Cui Categories: matlab Tags:


June 27th, 2016

Manish Saggar in our lab brought something very cool - a helmet like EEG system. He called it “dry” EEG because it does not requite gel. The design is not polished, but it’s cheap, like $800. And it does not need long wires to transmit the signal to a computer, which is pretty nice. This product is manufactured by OpenBCI, an open source community.


Manish Saggar

I decided to give it a try and borrowed the device from Manish.

Wearing OpenBCI Biosensing Headset

Wearing OpenBCI Biosensing Headset

The headset does not fit my head perfectly, leaving most channels in the front untouched with my head. It’s also not comfortable to wear for a long time; the material is hard and exert a lot of pressure on my head. But it’s wireless and we can collect the data and display the signal on screen in real time. This part is cool.

To collect data, we need two pieces of software and a USB dongle.

USB dongle

USB dongle

First, let’s download the dongle driver. The driver of the dongle can be found at Since I am using Windows 7, I download the Windows executable setup version. You can download the file ( directly from Then unzip and install it.

Then, let’s plugin the dongle into a USB. Make sure you plug it the right way. If you do, the dongle will emit blue lights. I did it wrong in the first place and have to reverse the side and try again.

We also need to download the OpenBCI software which can collect and visualize the data in real time. You can download it at I downloaded the Windows 64bit version.

Now it is time to play with it. First let’s open OpenBCI software.



The dongle acts as COM3 port on my computer, so I select COM3. I also switch my headset power on. Then I click “START SYSTEM”.



At this time I click the round “head” bring up the signal panel. Then I click “Start data stream” to collect the data. The figure below shows my brain wave in real time!

OpenBCI data collection

OpenBCI data collection

So far it’s all impressive. The setup is easy. But the question is if the signal is reliable. What we found is that it’s highly motion sensitive. If I move my head, or blink my eye, the signal will change. At this point, I hesitate to draw any conclusion on the quality of the signal.

In the past few years a number of companies have produced consumer-use brain signal recording devices. Check out this list in wikipedia. A few NIRS companies (e.g. Hitachi) are also working on a consumer NIRS device. There is no doubt that we will have a reliable personal brain sensor in the near future.

Author: Xu Cui Categories: brain Tags: