Reading the required variables for a function

Is there a function that will read the number and names of variables needed to run a function. I'm working on a brute force solution now that just opens the function as a text file and searches for the function declaration then reads the strings between the parenthesis.

2 件のコメント

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 5 日
Do you want the number of variables or their names?
Adam
Adam 2013 年 11 月 5 日
Both, your answer is a viable option, but I don't see how it will read the variables if the function call is not the first line of the .m file.

サインインしてコメントする。

回答 (3 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 5 日
編集済み: Azzi Abdelmalek 2013 年 11 月 5 日

0 投票

fid = fopen('file.m');
line=''
while isempty(line)
line=fgetl(fid)
end
fclose(fid);
v=regexp(line,'(?<=\().+(?=\))','match')
n=strfind(v{1},',') % number of variables
%If you want their names
w=regexp(v{1},',','split')

6 件のコメント

Adam
Adam 2013 年 11 月 5 日
This is great unless the function call is not on the first line of the code.
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 5 日
編集済み: Azzi Abdelmalek 2013 年 11 月 5 日
the test while isempty(line) checks if the first lines are empty
Walter Roberson
Walter Roberson 2013 年 11 月 5 日
編集済み: Walter Roberson 2013 年 11 月 5 日
Remember comment lines, and comments more generally.
Watch out for continuation lines.
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 5 日
For comment we can add a test
if line(1)=='%'
line=''
end
Walter Roberson
Walter Roberson 2013 年 11 月 5 日
Comments can start anywhere on a line. Also, blanks are permitted on lines.
line = regexprep(line, {'%.*', '^s+'}, {'', ''});
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 5 日
The first character of line is always different from ' '

サインインしてコメントする。

Adam
Adam 2013 年 11 月 5 日
編集済み: Adam 2013 年 11 月 5 日

0 投票

Thanks for the help Azzi. I never used the regexp function before. It works really well in this application.
function [nvars,vars] = req_variables(filename)
% % Open the file for reading only.
[fid,msg] = fopen(filename,'r');
if fid <= 0
disp('Was not able to open file');
disp(msg)
return;
end
% Read the file, line by line, until we find the function call
line = ' ';
while (~strcmp(line(1:8),'function'))
line = fgetl(fid);
end
% Read the variable names and number from the line
v=regexp(line,'(?<=\().+(?=\))','match');
nvars =strfind(v{1},','); % number of variables
vars=regexp(v{1},',','split');
%Close the file
fclose(fid);

カテゴリ

ヘルプ センター および File ExchangeVariables についてさらに検索

質問済み:

2013 年 11 月 5 日

コメント済み:

2013 年 11 月 5 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by