鉴于Matlab源代码,如何提取其中使用的所有函数和变量名?
上下文:我想找到一个匿名函数句柄的所有依赖项,不包括它的参数。 例如:
y=2;
anon = @(x) f1(x,y);
f1和y是我感兴趣的标识符。
答案 0 :(得分:1)
我对matlab不太熟悉,但我想出了这个正则表达式模式来找到matlab代码中的所有变量:
(?!(?:for|if|end)\b)\b[A-Za-z_]\w*\b(?!(?:[^']*'[^']*')*[^']*'[^']*$)
然而,对于正则表达式而言,这比查找除函数参数之外的所有变量更容易。如果您无法访问强大的正则表达式实现,则需要付出一些努力。我不知道你想用什么编程语言,但这里有它的要点:
使用此正则表达式模式查找所有匿名函数:
@\(\s*\w+(?:\s*,\s*\w+)*\s*\).*?;
对于每个匿名函数:
@\(.*?\)
来提取函数头,然后使用上述模式提取所有变量。\).*
模式将提取匿名函数的主体。接下来,再次从函数体中提取所有变量。正则表达式模式的说明:
找到变量:(?! // assert this isn't a keyword like "for" or "if"
(?:for|if|end)
\b
)
\b // in order for the previous assertion to work, we must now match a word boundary.
// Otherwise, the "or" in "for", the "nd" in "end", etc. would still match.
[A-Za-z_] // now, match a word character
\w* // and any more subsequent word characters and digits
\b // up to the next word boundary (this isn't really necessary, but I believe it makes the pattern faster)
(?! // finally, assert this word is not enclosed in quotes ''
// we'll count how many single quotes ' there are in this line
(?: // consume as many pairs of single quotes as possible
[^']*'
[^']*'
)*
[^']*' // consume one last single quote
[^']*$ // and make sure there are no more single quotes in this line
)
找到匿名函数:
@\( // match "@("
\s* // whitespace
\w+ // consume the first parameter
(?: // consume subsequent parameters, if any:
\s* // whitespace
, // a comma
\s* // some more whitespace
\w+ // and the next parameter
)*
\s* // whitespace again
\) // closing brace, end of parameter list
.*? // now simply consume the function body: everything...
; //...up to the next semicolon.
答案 1 :(得分:1)
刚发现有一个名为functions
的matlab命令看起来像你想要的那样
>> f1 = @(x) prod(x, y);
>> y = 2;
>> functions(f1)
ans =
function: '@(x)prod(x,y)'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> ans.workspace{1}
ans =
y: 2
如果您想要下面的所有依赖项,您可以在配置文件模式下运行该功能
profile on;
f1(3);
S = profile('info'). S.FunctionTable.FunctionName will have all of the functions that get called during execution of the anonymous function.