Part.I Introduction
本篇博文主要记录一下 Matlab 有关字符串的一些操作,会不断充实和丰富的~
Part.II 针对性功能实现
Chap.I 字符串比较
今天遇到一个问题,想用Matlab比较两个字符串的大小,以为用>、<、==
即可,谁知道这些比较符号返回的是一个逻辑矩阵(并且一般还要求两个字符串长度一致),在网上搜了下说加all()、any()
即可。确实,all 的意思是 【所有的都】,any 的意思是【只有一个就】,但是不能判断谁大谁小,matlab自带的strcmp 只能判断两个字符串是否相等(相等为真,否则为假),也不能判断谁大谁小,偶然发现一个前辈写了个函数,这个函数的功能类似于C语言中的strcmp:
- str1>str2, return 1
- str1==str2, return 0
- str1<str2, return -1
做点摘抄,以防下次再次入坑,函数如下:
function p=mstrcmp(str1,str2)
k=min(length(str1),length(str2));
for n=1:k %Compare the top k
if(str1(n)>str2(n))
p=1;break;
elseif(str1(n)==str2(n))
p=0;
else p=-1;break;
end
end
if(p==0)
if(length(str1)>length(str2)) %The first k bits are equal, but str1 is longer
p=1;
elseif(length(str1)==length(str2))
p=0;
else p=-1;
end
end
end
Chap.II 数字矩阵转字符串(元胞)矩阵
数字矩阵转换为字符串矩阵
function satlist=num2sat_char(sys,num)
%this function can trans numList to charSatList
satlist=[];
for i=num
satlist=[satlist;sys,num2str(i,'%02d')];
end
end
数字矩阵转换为元胞矩阵,元胞中存储的是字符串
function satlist=num2sat_cell(sys,num)
%this function can trans numList to cellSatList
satlist={};
for i=num
satlist=[satlist,cellstr([sys,num2str(i,'%02d')])];
end
end
Chap.II 查找字符串所在位置
补于 2021.3.23
查找某一字符串在字符串矩阵中的位置
function prn=find_sat_char(satlist,sat)
%this function can find the sat index from a charSatList
n=size(satlist,1);
prn=0;
for i=1:n
if mstrcmp(satlist(i,:),sat)==0
prn=i;
break;
end
end
end
function satlist=num2sat_char(sys,num)
%this function can trans numList to charSatList
satlist=[];
for i=num
satlist=[satlist;sys,num2str(i,'%02d')];
end
end
function p=mstrcmp(str1,str2)
%this function can strcap two str(>1 =0 <-1)
k=min(length(str1),length(str2));
for n=1:k %Compare the top k
if(str1(n)>str2(n))
p=1;break;
elseif(str1(n)==str2(n))
p=0;
else p=-1;break;
end
end
if(p==0)
if(length(str1)>length(str2)) %The first k bits are equal, but str1 is longer
p=1;
elseif(length(str1)==length(str2))
p=0;
else p=-1;
end
end
end
调用:
num=[1:3,5:32];
sys='G';
satlist=num2sat_char(sys,num);
sat='G30';
prn=find_sat_char(satlist,sat) %29
sat='G0';
prn=find_sat_char(satlist,sat) %0 can't find
ps:一看就知道我搞卫星的。
查找某一字符串在元胞矩阵中的位置
function p=mstrcmp(str1,str2)
%this function can strcap two str(>1 =0 <-1)
k=min(length(str1),length(str2));
for n=1:k %Compare the top k
if(str1(n)>str2(n))
p=1;break;
elseif(str1(n)==str2(n))
p=0;
else p=-1;break;
end
end
if(p==0)
if(length(str1)>length(str2)) %The first k bits are equal, but str1 is longer
p=1;
elseif(length(str1)==length(str2))
p=0;
else p=-1;
end
end
end
function satlist=num2sat_cell(sys,num)
%this function can trans numList to cellSatList
satlist={};
for i=num
satlist=[satlist,cellstr([sys,num2str(i,'%02d')])];
end
end
function prn=find_sat_cell(satlist,sat)
%this function can find the sat index from a cellSatList
n=length(satlist);
prn=0;
for i=1:n
if mstrcmp(satlist{i},sat)==0
prn=i;
break;
end
end
end
调用:
num=[1:3,5:32];
sys='G';
satlist=num2sat_cell(sys,num);
sat='G30';
prn=find_sat_cell(satlist,sat) %29
sat='G0';
prn=find_sat_cell(satlist,sat) %0