Search code examples
matlabcommand-line

suppress start message of Matlab


I want to call matlab in bash non-interactively and use its result outside Matlab.

For example, I have a script test.m

rand(3,4)
quit

When I execute in bash

$ matlab -nosplash -nodesktop -nodisplay -r test
Warning: No window system found.  Java option 'MWT' ignored

                        < M A T L A B (R) >
              Copyright 1984-2008 The MathWorks, Inc.
                     Version 7.7.0.471 (R2008b)
                         September 17, 2008


  To get started, type one of these: helpwin, helpdesk, or demo.
  For product information, visit www.mathworks.com.


ans =

0.8147    0.9134    0.2785    0.9649
0.9058    0.6324    0.5469    0.1576
0.1270    0.0975    0.9575    0.9706

Is it possible to suppress the start message of Matlab and only show the results also without "ans=".

Note I am asking a general question not just for this example.

Thanks and regards!


Solution

  • You could use the Unix command "tail +n" to remove the first n lines of output. That header looks like 10 lines, so this will strip it.

    $ matlab -nosplash -nodesktop -nodisplay -r test | tail +10
    

    This is a little fragile, though, since warnings (like that "no window system") will get stripped, and the header size will vary depending on what warnings happen (and those warnings are useful diagnostics). Also, that warning might be on STDERR instead of STDOUT, so "tail +9" might be what you need.

    A more robust approach could be to modify the Matlab script to write to a separate file using fopen/fprintf/fclose. That way the header, warnings, errors, etc from Matlab will be separated from the formatted output you want. To get the "disp" output to go to that separate file handle, you can capture it using evalc. The outfile could be specified using an argument to test() in the -r message, and the $$ env variable (the bash process's PID) incorporated in the file name to prevent collisions in a multiprocess environment.

    function test(ppid)
    outfile = sprintf('outfile-%d.tmp', ppid);
    fh = fopen(outfile, 'w');
    myvar = rand(3,4);
    str = evalc('disp(myvar)');
    fprintf(fh, '%s', str);
    fclose(fh);
    

    To invoke it from bash, use this calling form. (May be minor syntax problems here; I don't have a Unix box to test on right now.)

    % matlab -nosplash -nodisplay -r "test($$)" -logfile matlab-log-$$.tmp
    

    Let's say your bash PID is 1234. Now you've got your output in outfile-1234.tmp and a Matlab log in matlab-log-1234.tmp. Stick them in /tmp if you don't want to be dependent on pwd. You could extend this to create multiple output files from a single matlab invocation, saving the startup costs if you need to compute multiple things.