Matlab-如何在函数内部以字符串的形式检索函数调用的确切参数列表? [英] Matlab - how to retrieve the exact parameter list of the function call as a string inside the function?

查看:125
本文介绍了Matlab-如何在函数内部以字符串的形式检索函数调用的确切参数列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下功能:

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

基本上我想做的是打电话给

Basically what I want it to do is, calling:

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

应在屏幕上打印字符串:

should print to the screen the string:

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

有什么建议吗?

ETA:我想要这样的原因是希望能够解决此问题: Matlab-如何创建数据集类的子类,保留数据集参数构造函数

ETA: The reason I want something like this is to hopefully resolve this question: Matlab - how to create a subclass of dataset class keeping the dataset parameter constructor

推荐答案

好吧,如果您在命令行中键入此函数调用或以F9运行(这样它将保存在历史记录中),则可以读取history.m文件并以字符串形式获取最后一个命令.

Well, if you type this function call in a command line or run with F9 (so it get saved in the history) you can read the history.m file and get the last command as a string.

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

然后获取参数部分:

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

更新:

另一个想法.如果从另一个脚本或函数(m文件)调用此函数,则可以使用 DBSTACK 返回m文件名和当前行号:

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

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

然后,您可以按照与第一种解决方案类似的技术从m文件读取该行并获取参数部分.

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

与第一种解决方案相反,如果从命令行或编辑器单元模式下运行,则此方法将无效.

In opposite to the first solution this won't work if run from command line or editor cell mode.

这篇关于Matlab-如何在函数内部以字符串的形式检索函数调用的确切参数列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆