网站建设论文百度云盘,外贸网站建设方案,企业信息公开网查询,网站的主机空间是文章目录Part.I 元胞相关Chap.I 创建空 char 型元胞Part.II 矩阵相关Chap.I 矩阵插入元素Part.III 字符串相关Chap.I 获取一个文件夹下所有文件的文件名的部分内容Part.IV 结构体相关Chap.I 读取结构体Chap.II 取结构体中某一字段的所有值本篇博文记录一些笔者使用 Matlab 时根据自己的需求编写的一些小函数。
Part.I 元胞相关
Chap.I 创建空 char 型元胞
matlab可以创建空元胞矩阵cell(a,b);只不过创建好之后里面存储的类型是空double笔者想要创建一个空元胞矩阵且里面存放的数据类型是char所以笔者编写了这样一个函数
% get a null cell which is a*b dims
function datakcell(a,b)
datacell(a,b);
for i1:afor j1:bdata(i,j)cellstr(num2str(data{i,j}));end
end
endPart.II 矩阵相关
Chap.I 矩阵插入元素
Matlab 在一个行向量/列向量某个位置处插入一个值
% insert num at ind in mat
function datainsert(mat,ind,num)
nlength(mat);
data(ind)num;
data(1:ind-1)mat(1:ind-1);
data(ind1:n1)mat(ind:n);
endPart.III 字符串相关
Chap.I 获取一个文件夹下所有文件的文件名的部分内容
最近搞事情想从一个目录中提取所有文件的文件名中前几个字符并转换为char。原来发现我一直存在一个误区“ 和引起来的东西是相同的”。今天才发现是不同的然后又学到了一写新的东西比如元素取唯一获取目录中所有文件的名字……
% get sitename from a dir
function sitegetSite_dir(enudir)
dirOutput dir(fullfile(enudir));% 此行下面一行获取目录所有文件名
plyName {dirOutput.name}; % get a cell mat
plyName plyName(3:end); % rm . and ..
nlength(plyName);
sitelist;
for i1:nfnameplyName{i};siteliststrcat(sitelist, ,fname(1:4));
end
sitelistunique(regexp(strtrim(sitelist), \s, split));
%string2char
nsitelength(sitelist);
site[];
for i1:nsitetmpchar(sitelist(i));tmplower(tmp);site[site;tmp];
end
end注regexp是以空格为分隔符将str变为str array。char是用单引号引起来的字符串string是用双引号引起来的字符串两者之间的转化用它们的名字即可char合并用[]string合并用strcmp。
Part.IV 结构体相关
Chap.I 读取结构体
比如我现在想读取这样一个文件到结构体中。文件内容如下
name sex age hobby
aa man 4 8
ab wom 5 9
bb wom 6 10
cc man 7 11实现函数如下
% get struct from clkdif file
function sturead_dif(file)
fidfopen(file,r);
str fgetl(fid);
S regexp(str, \s, split); %field
nlength(S);
j1;
while ~feof(fid)str fgetl(fid);strstrtrim(str); %rm the blankSpace on the beg and endif str(1)-continue;endif str(1:3)EOFbreak;endtmp regexp(str, \s, split);for i1:neval([stu(j).,S{i},tmp{i};]);endjj1;
end
fclose(fid);
end调用示例
clc;clear;
fileC:\Users\OHanlon\Desktop\a.txt;
tic;
sturead_dif(file);
toc;Chap.II 取结构体中某一字段的所有值
可以和上面的函数配合使用
% get the field value from sta
function dataget_fdata(sta,field)
data[];
affieldnames(sta);
nlength(af);
for i1:nif mstrcmp(af{i},field)0break;end
end
if (mstrcmp(af{i},field)~0)disp(----error----);disp([The filed ,field, is not in sta!]);disp(------end----);return;
end
mlength(sta);
for i1:mdataeval([[data;sta(i).,field,];]);
end
end