需求
我用Matlab写代码时候,经常想把许多重复性的操作写成函数,但是在Matlab有工作空间里可能存在命名冲突的问题,比如写一个画矩形的函数rectangle,Matlab里已经有这个函数了,一个解决的办法是把这些自己写的函数都放到一个类里去当做静态函数调用,函数前面加上类名,就不会冲突了。
类里写静态函数的方法有两个:
- 直接在类定义文件,即有classdef的文件里写
classdef sp
methods (Static)
function [] = func1()
end
function [] = func2()
end
end
end
像上面这样写,就可以写很多个函数,调用的时候只要用sp.func1就行了。但这样会存在一个问题,如果函数的代码量很大的话,再把这些函数都写在类定义文件里就显得臃肿。
2. 在类定义文件放在@class文件夹里,上面的就写@sp,在@sp文件夹里写的函数就只有sp类才能调用了,
假设func1.m里写了函数
function [] = func1()
end
那只要在类定义文件里加上
classdef sp
methods (Static)
[] = func1()
end
end
就可以了,但是这样又有一个问题,假如函数的声明发生了变化,我又得把改变了的函数声明拷贝到类定义文件里,非常麻烦。所以我就想写一m文件,把改变了的函数声明用代码写到类定义文件里。
实现思路
将类定义文件sp.m中放函数声明的前面加上一句注释begin_of_out_file,末尾加一句注释end_of_out_file
判断是否含有某个字符串
contains(str1,str2)
读取文本文件的行
tline = fgetl(fid)
一行一行读下来,发现有begin_of_out_file的时候,将@sp文件夹下的所有m文件读进来
funcList = dir([input_path,'/*.m']);
func_str = '';
for k = 1:length(funcList)
if strcmp(funcList(k).name,name)==0&&...
strcmp(funcList(k).name,new_name)==0
fid = fopen(fullfile(funcList(k).folder,...
funcList(k).name),'r');
tline = fgetl(fid);
tline = strrep(tline,'function ',repmat(' ',1,8));
func_str = sprintf('%s%s\n',func_str,tline);
end
end
删除字符串
tline = erase(tline,'function ');
替换字符串
tline = strrep(tline,'function ',repmat(' ',1,8));
读取所有函数的第一行,将function替换成空格,再写到新文件中去,同时,begin_of_out_file和end_of_out_file之间的将摒弃掉。
注意事项
- 为了防止写错,留了个备份文件
- 本来最后想用movefile用新文件替换旧文件的,但报错文件正在使用
完整代码
clear;close all;clc
%%
input_path = 'E:\MatlabCode\Resonator\code\@sp\';
%%
name = 'sp.m';
new_name = 'sp_1.m';
orgname = fullfile(input_path, name);
dstname = fullfile(input_path, new_name);
backup_name = fullfile(input_path,'sp.txt');
copyfile(orgname,backup_name);
fr = fopen(orgname,'r');
fw = fopen(dstname,'w');
%%
while true
tline = fgetl(fr);
if tline == -1
break;
end
flag = contains(tline,'begin_of_out_file');
if ~flag
fprintf(fw,'%s\r\n',tline);
else
fprintf(fw,'%s\r\n',tline);
funcList = dir([input_path,'/*.m']);
func_str = '';
for k = 1:length(funcList)
if strcmp(funcList(k).name,name)==0&&...
strcmp(funcList(k).name,new_name)==0
fid = fopen(fullfile(funcList(k).folder,...
funcList(k).name),'r');
tline = fgetl(fid);
tline = strrep(tline,'function ',repmat(' ',1,8));
func_str = sprintf('%s%s\n',func_str,tline);
end
end
fprintf(fw,'%s\r\n',func_str);
while 1
tline = fgetl(fr);
flag = contains(tline,'end_of_out_file');
if flag == 1
fprintf(fw,'%s\r\n',tline);
break;
end
end
end
end
%%
fclose(fr);
fclose(fw);
%%
movefile(dstname,orgname)