腐姬呀 发表于 2014-8-23 10:46

matlab错误提示说非法使用保留关键字

现在是设计一个把多项式的字符串转换成行向量表示的函数,错误如图所示(非法使用关键字 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=;%单项多项式字符串为 ‘x^*' 形式
                power=;
            elseif(index2(1)==2)
                if (substring(1)=='+')
                    cofficient=;
                    power=;
                elseif(substring(1)=='-')
                    cofficient=;
                    power=;
                end;
            end;
            coefficient=;
            power=;
        end;
        else
            index2=regexp(substring,'x');
            if (isempty(index2)==0)
                if (index2(1)==1)
                    cofficient=;
                    power=;
                elseif(index2(1)==2)
                       if ((substring(1)=='+')==1)
                           cofficient=;
                           power=;
                       elseif (substring(1)=='-')
                           cofficient=;
                           power=;
                       else
                           cofficient=;
                           power=;
                       end;
                else
                    cofficient=;
                    power=;
                end;
            else
             cofficient=;
            power=;
            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;

腐姬呀 发表于 2014-8-23 11:00

源码居然变成了表情,还是上传M文件吧:L

madio 发表于 2014-8-23 13:32

else上面不该出现一个end呀

腐姬呀 发表于 2014-8-23 14:47

madio 发表于 2014-8-23 13:32 static/image/common/back.gif
else上面不该出现一个end呀

可是不要上面那个end,错误又提示说至少缺少一个end。语句可能从第11句的 fori=1:L-1开始

腐姬呀 发表于 2014-8-23 15:49

madio 发表于 2014-8-23 13:32 static/image/common/back.gif
else上面不该出现一个end呀

站长,再问一句,matlab2014a中把字符串转换成矩阵用什么函数,str2num它说我没定义~:'(

腐姬呀 发表于 2014-8-23 16:12

腐姬呀 发表于 2014-8-23 15:49 static/image/common/back.gif
站长,再问一句,matlab2014a中把字符串转换成矩阵用什么函数,str2num它说我没定义~

:L有,原谅我又把单词打错了:'(
页: [1]
查看完整版本: matlab错误提示说非法使用保留关键字