- 在线时间
- 128 小时
- 最后登录
- 2016-1-12
- 注册时间
- 2014-8-14
- 听众数
- 14
- 收听数
- 0
- 能力
- 0 分
- 体力
- 483 点
- 威望
- 0 点
- 阅读权限
- 30
- 积分
- 213
- 相册
- 0
- 日志
- 0
- 记录
- 0
- 帖子
- 140
- 主题
- 9
- 精华
- 0
- 分享
- 0
- 好友
- 42
升级   56.5% TA的每日心情 | 郁闷 2015-2-4 00:27 |
---|
签到天数: 64 天 [LV.6]常住居民II
- 自我介绍
- 新人
 群组: 国赛讨论 |
现在是设计一个把多项式的字符串转换成行向量表示的函数,错误如图所示(非法使用关键字 else)。
贴上源码,原谅我后面的没写注释,就别看后面的了。
代码:
%str2poly.m
%把多项式的字符串转换成行向量表示
function Y=str2poly(X)
if (ischar(X)==0)%格式检查
disp('输入错误,输入X必须是一个字符串!');
end;
index=regexp(X,'\+|\-');%用正则表达式寻找+或-的下标位置,|表示或
L=length(index);%多项式的项数
term=cell(1,L+1);%用于储存多项式每一项信息的单元字符串矩阵,cell(1,L+1)表示创建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)));
if (isempty(char(term(1)))) %如果第一项为空,则删除第一项
term(1)=[];
L=L-1;
end;
coefficient=[];%多项式系数矩阵
power=[]; %多项式幂次矩阵,它与多项式系数矩阵一一对应
for i=1:L+1
substring=char(term(i));%单项多项式字符串表达式
index2=regexp(substring,'\^');
if (isempty(index2)==0)
if (index2(1)==1) %如果匹配上
coefficent=[coefficient 1];%单项多项式字符串为 ‘x^*' 形式
power=[power str2num(substring((index2(1)+2):end))];
elseif(index2(1)==2)
if (substring(1)=='+')
cofficient=[coefficent 1];
power=[power str2num(substring((index2(1)+2):end))];
elseif(substring(1)=='-')
cofficient=[coefficent -1];
power=[power str2num(substring((index2(1)+2):end))];
end;
end;
coefficient=[coefficent str2sum(substring(1:(index2(1)-1)))];
power=[power str2num(substring((index2+2):end))];
end;
else
index2=regexp(substring,'x');
if (isempty(index2)==0)
if (index2(1)==1)
cofficient=[coefficent 1];
power=[power 1];
elseif(index2(1)==2)
if ((substring(1)=='+')==1)
cofficient=[coefficent 1];
power=[power 1];
elseif (substring(1)=='-')
cofficient=[coefficent -1];
power=[power 1];
else
cofficient=[cofficient str2num(substring(1:(index2-1)))];
power=[power 1];
end;
else
cofficient=[cofficient str2num(substring(1:(index2-1)))];
power=[power 0];
end;
else
cofficient=[cofficient 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; |
zan
|