How to read from stdin in Matlab

不想你离开。 提交于 2019-12-06 05:48:26

问题


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.



来源:https://stackoverflow.com/questions/23875734/how-to-read-from-stdin-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!