Find a specific symbol at the beginning of a .m file
I am new to Matlab and I am trying to write a program that needs to look for a pipe symbol |
before a function is declared in a .m file.
For example:
% |
function y = add(x,z)
y = x+z
end
I have an idea on how to proceed, but I cannot write the code for it:
- Request a file for the file to be parsed
- Open the file
- Skip any blank lines at the beginning of the file
- Extract the first comment before the function declaration, proceed depending on the presence of the symbol
|
What I have managed to put into the code so far:
function y = filesearch()
%Ask user for file to parse
[fileName, filePath] = uiputfile('*.m','Choose file you want to parse');
% Open the file:
fid = fopen(filePath);
% Skip empty lines:
defLine = '';
while all(isspace(defLine))
defLine = strip_comments(fgets(fid));
end
% Check for presence of |
As you can see, I cannot think of a line that can strip the comment (if it exists) and check for the pipe symbol.
Also, although not a priority right now , I would like to use this character at the end of each line if it satisfies certain parameters. For example:
Algebraic
(No character at the end of the line)
R1 = 1; R2 = 2; R3 = 3;
Rs = R1 + R2 + R3;
Differential
(| at the end of the dydt statement)
% |
function dydt = vanderpoldemo(t,y,Mu)
%VANDERPOLDEMO Defines the van der Pol equation for ODEDEMO.
dydt = [y(2); Mu*(1-y(1)^2)*y(2)-y(1)]; % |
For the above-mentioned differential case, I think, need a regular expression (after intial |
will be found before the announcement function), to check availability |
at the end of the line, in which an ad is not algebraic.
I would appreciate any help or advice on how to extract and verify the original comment, and if possible how can I implement my additional question where should I check if a character exists at the end of each line.
source to share
The following code loops through the line of the line and looks for a comment character in the comment. It stops after it has been found:
fid = fopen('add.m');
% Check for presence of | in a comment
tline = fgetl(fid);
while ischar(tline)
if strfind(tline,'%') % find comments
if strfind(tline,'|') % find pipe
disp(tline) % do something
break; % stop while loop
end
end
tline = fgetl(fid);
end
fclose(fid);
source to share