【MATLAB】将向量表示的多项式用字符串输出的通用函数示例

%创建一个名为pprintf的M文件
function s = pprintf(p)
%UNTITLED7 此处显示有关此函数的摘要
%   此处显示详细说明
if nargin>1
    error('Too much input arguments');
end
while(p(1)==0)
    p1=[];
end
l=length(p);
if l==0
    s='0';
elseif l==1
    s=num2str(p(1));
elseif l==2
    s = strcat(num2str(p(1)),'x+',num2str(p(2)));
elseif l>2
    for i =1:l
        if i==1
            if p(i)==1
                s = strcat('x^{',num2str(l-i),'}');
            else
                s = strcat(num2str(p(i)),'x^{',num2str(l-i),'}');
            end
        elseif i==l
             s = strcat(s,'+',num2str(p(i)));
        elseif i==(l-1)
            s = strcat(s,'+',num2str(p(i)),'x');
        else
            if p(i)==0
            else
                s = strcat(s,'+',num2str(p(i)),'x^{',num2str(l-i),'}');
            end
        end
    end         
end


%在另一个M文件中调用该函数
p=[1,2,3,4,5];
figure;
x=-5:1:5;
y=x.^4+2*x.^3+3*x.^2+4*x+5;
subplot(1,2,1);
plot(x,y,'k-','LineWidth',2);
title(pprintf(p))
subplot(1,2,2);
x=-2:1:1;
y=x.^4+2*x.^3+3*x.^2+4*x+5;
plot(x,y,'k-','LineWidth',2);
title(pprintf(p))

猜你喜欢

转载自blog.csdn.net/csdn___csdn/article/details/81153853