📄 str2poly.m
字号:
function Y=str2poly(X)
%X是字符串形式的多项式
%Y是行向量形式的多项式
%输入格式检查
if(ischar(X)==0)
disp('输入错误:输入X必须是一个字符串!');
end;
%用正则表达式寻找'+'或者'-'的下标位置
index=regexp(X,'\+|\-');
%多项式的项数
L=length(index);
%用于存储多项式每一项信息的单元字符串矩阵
term=cell(1,L+1);
term(1)=cellstr(X(1:(index(1)-1)));
for i=1:L-1,
term(i+1)=cellstr(X(index(i):(index(i+1)-1)));
end;
term(L+1)=cellstr(X(index(L):end));
%如果第一项为空,则删除该项
if(isempty(char(term(1))))
term(1)=[];
%多项式的项数减一
L=L-1;
end;
%多项式系数矩阵
coefficient=[];
%多项式幂次矩阵,它与多项式系数矩阵一一对应
power=[];
for i=1:L+1,
%单项多项式字符串表达式
substring=char(term(i));
%用正则表达式,寻找字符串'x^',由于'^'是正则表达式中的特殊字符,多以用'\^'来表示
index2=regexp(substring,'x\^');
if(isempty(index2)==0),
%如果匹配上后
if(index2(1)==1),
%单项多项式字符串为'x^*'形式
coefficient=[coefficient 1];
power=[power str2num(substring((index2(1)+2):end))];
elseif(index2(1)==2),
%单项多项式字符串为'+x^*'或者'-x^*','3x^*'形式
if(substring(1)=='+'),
coefficient=[coefficient 1];
power=[power str2num(substring((index2(1)+2):end))];
elseif(substring(1)=='-'),
coefficient=[coefficient -1];
power=[power str2num(substring((index2(1)+2):end))];
else
coefficient=[coefficient str2num(substring(1:(index2(1)-1)))];
power=[power str2num(substring((index2+2):end))];
end;
else
%单项多项式字符串为'2.2x^*'
coefficient=[coefficient str2num(substring(1:(index2(1)-1)))];
power=[power str2num(substring((index2+2):end))];
end;
else
%单项多项式字符串不含'x^'
%用正则表达式,寻找字符串'x'
index2=regexp(substring,'x');
if(isempty(index2)==0),
%如果匹配上'x'
if(index2(1)==1),
%单项多项式字符串为'x*'形式
coefficient=[coefficient 1];
power=[power 1];
elseif(index2(1)==2),
%单项多项式字符串为'+x*'或者'-x*','3x*'形式
if((substring(1)=='+')==1),
coefficient=[coefficient 1];
power=[power 1];
elseif(substring(1)=='-'),
coefficient=[coefficient -1];
power=[power 1];
else
%单项多项式字符串为'2.2x*'
coefficient=[coefficient str2num(substring(1:(index2-1)))];
power=[power 1];
end;
else
coefficient=[coefficient str2num(substring(1:(index2-1)))];
power=[power 1];
end;
else
%单项多项式字符串不含'x^','x',则断定它是常数项
coefficient=[coefficient str2num(substring)];
power=[power 0];
end;
end;
end;
N=max(power)+1;
Y=zeros(1,N);
for i=1:N,
index3=find(power==(N-i));
Y(i)=sum(coefficient(index3));
end;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -