Get command line arguments in matlab

This is probably too simple, but I can't answer this Google question: how can I get command line arguments in a matlab script.

I run matlab as matlab -nodisplay -r "run('script.m')", and I want to return all arguments as a list. Something similar to python sys.argv. How can i do this?

I am using Linux Mint and MATLAB 2015a.

+4
source share
2 answers

I came up with a simple function that works on both Windows and Linux (Ubuntu):

function args = GetCommandLineArgs()

if isunix
    fid = fopen(['/proc/' num2str(feature('getpid')) '/cmdline'], 'r');
    args = textscan(fid, '%s', 'Delimiter', char(0));
    fclose(fid);
else
    kernel32WasAlreadyLoaded = libisloaded('kernel32');
    if ~kernel32WasAlreadyLoaded
        temporaryHeaderName = [gettempfolder '\GetCommandLineA.h'];
        dlmwrite(temporaryHeaderName, 'char* __stdcall GetCommandLineA(void);', '');
        loadlibrary('kernel32', temporaryHeaderName);
        delete(temporaryHeaderName);
    end
    args = textscan(calllib('kernel32', 'GetCommandLineA'), '%q');
    if ~kernel32WasAlreadyLoaded
        unloadlibrary kernel32;
    end
end

args = args{1};

In your model call, it will return this:

>> GetCommandLineArgs

args = 

    '/[path-to-matlab-home-folder]/'
    '-nodisplay'
    '-r'
    'run('script.m')'

It returns an array of row cells, where the first row is the path to the MATLAB home folder (on Linux) or the full path to the MATLAB executable (on Windows), and the rest are the program arguments (if any).

:

+3

(, ). :

1.

Linux:

pid_wrapper.m :

function [] = pid_wrapper( parent_pid )

[~, matlab_pid] = system(['pgrep -P' num2str(parent_pid)]);
matlab_pid = strtrim(matlab_pid);
[~, matlab_args] = system(['ps -h -ocommand ' num2str(matlab_pid)]);
matlab_args = strsplit(strtrim(matlab_args));
disp(matlab_args);

% call your script with the extracted arguments in matlab_args
% ...

end

MATLAB :

matlab -nodisplay -r "pid_wrapper($$)"

MATLAB (.. , MATLAB), wrapper. MATLAB , matlab_args.

2.

, script, .

vararg_wrapper.m :

function [] = wrapper( varargin )

% all parameters can be accessed in varargin
for i=1:nargin
    disp(varargin{i});
end

% call your script with the supplied parameters 
% ...

end

MATLAB :

matlab -nodisplay -r "vararg_wrapper('first_param', 'second_param')"

{'first_param', 'second_param'} vararg_wrapper, script.

+2

All Articles