Matlab - how to get a list of exact parameters of a function call as a string inside a function?

Suppose I have a function:

function name_the_paramlist(varargin)
    % Print out varargin exactly how it is called as a string


Basically what I want to do is call:

name_the_paramlist({'x', x}, y, 1, 'hello', [1, 2; 3, 4])


should print the line on the screen:

'{''x'', x}, y, 1, ''hello'', [1, 2; 3, 4]}'


Any suggestion?

ETA: The reason I want something like this is hopefully to resolve this issue: Matlab - how to subclass dataset class that supports dataset parameter constructor


source to share

1 answer

Well, if you enter this function call on the command line, or run with F9 (so it will be stored in history), you can read the file history.m

and get the last command as a string.

fid = fopen(fullfile(prefdir,'history.m'),'rt');
while ~feof(fid)
    lastcmd = fgetl(fid);


Then get part of the argument:

arg_str = regexp(lastcmd, '\w+\((.+)\)','tokens','once');
arg_str = strrep(arg_str{:},'''','''''');



Another idea. If you call this function from another script or function (m-file), you can use DBSTACK to return the file name m and the current line number:

SI = dbstack;
filename = SI(end).file;
lineNo = SI(end).line;


Then you can follow a similar technique as in the first solution, read that line from m file and get a part of the argument.

Unlike the first solution, this won't work if you run from command line or cell mode of the editor.



All Articles