-->

How to read from stdin in Matlab

2020-07-18 02:45发布

问题:

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?

回答1:

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.



回答2:

One way to do this is using a named pipe. In a shell, run mkfifo MY_PIPE to make a named pipe. This will make a file-like object called MY_PIPE that you can read and write to. Then, redirect the output of the program sending data to MY_PIPE, e.g. ./program.sh > MY_PIPE. Finally, to read from the pipe in Matlab, you can use fopen('MY_PIPE', 'r').

Note that answer is limited in a few ways:

  1. It will only run in a Linux environment and with access to the shell.

  2. It doesn't make use of Matlab built-ins and is kind of hackish.