Surpress output when calling matlab live script from other live script

Viewed 278

I have a live script (main.mlx) that is calling two other live scripts (sub1.mlx, sub2.mlx). I want the output to be shown when calling the subscripts by themself but not when I call the main script, though I want to display something in the main script. I tried to put a semicolon behind the subscript calls in main script.

Minimum working example

main.mlx:

clear vars

sub1;
sub2;

sub1.mlx:

syms A1 B1

A1 = B1

sub2.mlx:

syms A2 B2

A2 = B2

Expected output: None

Output:

enter image description here

What I tried (unsuccessfully):

clear vars

run('sub1.mlx');
run('sub2.mlx');
2 Answers

One solution is:

clear vars
out1=evalc('sub1');
out2=evalc('sub2');

where out1 and out2 are optional to catch the output.

The following golden rule can be applied to any MATLAB coding, and is applicable here

Always suppress the display of assignments using ;, and explicitly display variables separately when required.

In this case, we can do the following:

  • Inside main.mlx, we write

    % Call the sub scripts without output
    bDisp = false;
    sub1; 
    sub2;
    
  • Inside sub1.mlx and sub2.mlx, you can structure your outputs to be more explicit

    % By default (when running this script alone), display things
    if ~exist( 'bDisp', 'var' )
        bDisp = true;
    end
    
    syms A1 B1
    % Terminate the assignment with a semi-colon to suppress output
    A1 = B1;
    % Explicitly display A1 here (if bDisp is enabled)
    if bDisp
        A1 % disp(A1) would be even more verbose, but doesn't show "A1 = "
    end
    

This method gives you control over when to display things, regardless where you're calling them from.

You could make the default check (at the top of sub1.mlx/sub2.mlx) more complicated if you want. For instance you could use dbstack to determine where the executing code was called from (i.e. which function), but live scripts get a bit funky with the stack.

Related