?? str2poly.m
字號:
function Y=str2poly(X)
%X是字符串形式的多項式
%Y是行向量形式的多項式
%輸入格式檢查
if(ischar(X)==0)
disp('輸入錯誤:輸入X必須是一個字符串!');
end;
%用正則表達式尋找'+'或者'-'的下標(biāo)位置
index=regexp(X,'\+|\-');
%多項式的項數(shù)
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)=[];
%多項式的項數(shù)減一
L=L-1;
end;
%多項式系數(shù)矩陣
coefficient=[];
%多項式冪次矩陣,它與多項式系數(shù)矩陣一一對應(yīng)
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',則斷定它是常數(shù)項
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;
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -