How to read from stdin in Matlab

ipc, matlab, matlab-deployment

Solution

It actually turns out that the solution is as simple as `input`. Write the following into myscript.m:

str = input('', 's'); 
fprintf(str); 
exit;

Then, run the following in a shell:

`echo Hello world | matlab -nosplash -nodisplay -nodesktop -r "myscript"`

Indeed, we see that "Hello world" is printed to the console, along with Matlab's startup text.

So, in summary, `input` reads from stdin, and `fprintf` writes to stdout.

Problem

I have a long-running Matlab script for data processing. I want to send it a flag over stdin to tell it I have new data to process. I also want to read a flag from stdout when it is done processing. In other words, I have a Process A that sends a flag about once a minute to Matlab. I want Matlab to wait until it receives this flag. Writing to stdout in a matlab process is as easy as calling `fprintf`. But how can I read from stdin? Documentation on `fopen` doesn't mention an input pipe, and neither does `fread`. How can get a Matlab script to read from stdin?

Original source