如何在matlab中搜索函数名,如何在MATLAB中检索函数参数的名称?

如果您的问题仅限于要解析文件中

primary function的

function declaration line(即您不会处理

subfunctions,

nested functions或

anonymous functions)的简单情况,则可以将输入和输出参数名称解​​析为它们使用一些标准字符串操作和

regular expressions显示在文件中。函数声明行具有标准格式,但由于以下原因,您必须考虑以下几种变体:

(事实证明,占用块评论是最棘手的部分…)

我已经编写了一个函数get_arg_names,它将处理上述所有内容。如果给它一个函数文件的路径,它将返回包含输入和输出参数字符串的两个单元格数组(如果没有,则返回空单元格数组)。请注意,具有可变输入或输出列表的函数将分别列出变量名称的'varargin'或'varargout'。这是功能:

function [inputNames, outputNames] = get_arg_names(filePath)

%# Open the file:

fid = fopen(filePath);

%# Skip leading comments and empty lines:

defLine = '';

while all(isspace(defLine))

defLine = strip_comments(fgets(fid));

end

%# Collect all lines if the definition is on multiple lines:

index = strfind(defLine, '...');

while ~isempty(index)

defLine = [defLine(1:index-1) strip_comments(fgets(fid))];

index = strfind(defLine, '...');

end

%# Close the file:

fclose(fid);

%# Create the regular expression to match:

matchStr = '\s*function\s+';

if any(defLine == '=')

matchStr = strcat(matchStr, '\[?(?[\w, ]*)\]?\s*=\s*');

end

matchStr = strcat(matchStr, '\w+\s*\(?(?[\w, ]*)\)?');

%# Parse the definition line (case insensitive):

argStruct = regexpi(defLine, matchStr, 'names');

%# Format the input argument names:

if isfield(argStruct, 'inArgs') && ~isempty(argStruct.inArgs)

inputNames = strtrim(textscan(argStruct.inArgs, '%s', ...

'Delimiter', ','));

else

inputNames = {};

end

%# Format the output argument names:

if isfield(argStruct, 'outArgs') && ~isempty(argStruct.outArgs)

outputNames = strtrim(textscan(argStruct.outArgs, '%s', ...

'Delimiter', ','));

else

outputNames = {};

end

%# Nested functions:

function str = strip_comments(str)

if strcmp(strtrim(str), '%{')

strip_comment_block;

str = strip_comments(fgets(fid));

else

str = strtok([' ' str], '%');

end

end

function strip_comment_block

str = strtrim(fgets(fid));

while ~strcmp(str, '%}')

if strcmp(str, '%{')

strip_comment_block;

end

str = strtrim(fgets(fid));

end

end

end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值