print.m :
function [s t]=print(a)
s='';
t='';
len=length(a);
if (len==0)
errordlg('矩阵不能为空');
else
for b=1:len
if b~=len&&b~=len-1
if a(b)<0 && a(b)~=-1
s=strcat(s,num2str(a(b)),'x^',num2str(len-b));
t=strcat(t,num2str(a(b)),'*x.^',num2str(len-b));
elseif a(b)==-1
s=strcat(s,'-','x^',num2str(len-b));
t=strcat(t,'-','x.^',num2str(len-b));
elseif a(b)>0 && a(b)~=1
if b==1
s=strcat(s,num2str(a(b)),'x^',num2str(len-b));
t=strcat(t,num2str(a(b)),'*x.^',num2str(len-b));
else
s=strcat(s,'+',num2str(a(b)),'x^',num2str(len-b));
t=strcat(t,'+',num2str(a(b)),'*x.^',num2str(len-b));
end
elseif a(b)==1
if b==1
s=strcat(s,'x^',num2str(len-b));
t=strcat(t,'x.^',num2str(len-b));
else
s=strcat(s,'+','x^',num2str(len-b));
t=strcat(t,'+','x.^',num2str(len-b));
end
else
end
elseif b==len
if a(b)<0 && a(b)~=-1
s=strcat(s,num2str(a(b)));
t=strcat(t,num2str(a(b)));
elseif a(b)==-1
s=strcat(s,'-1');
t=strcat(t,'-1');
elseif a(b)>0 && a(b)~=1
s=strcat(s,'+',num2str(a(b)));
t=strcat(t,'+',num2str(a(b)));
elseif a(b)==1
s=strcat(s,'+1');
t=strcat(t,'+1');
else
end
else
if a(b)<0 && a(b)~=-1
s=strcat(s,num2str(a(b)),'x');
t=strcat(t,num2str(a(b)),'*x');
elseif a(b)==-1
s=strcat(s,'-','x');
t=strcat(t,'-','x');
elseif a(b)>0 && a(b)~=1
if b==1
s=strcat(s,num2str(a(b)),'x');
t=strcat(t,num2str(a(b)),'x');
else
s=strcat(s,'+',num2str(a(b)),'x');
t=strcat(t,'+',num2str(a(b)),'*x');
end
elseif a(b)==1
if b==1
s=strcat(s,'x');
t=strcat(t,'x');
else
s=strcat(s,'+','x');
t=strcat(t,'+','x');
end
else
end
end
end
end
end
main.m :
clear all;
clc;
x=-10:1:10;
a=[-2 -10 0 5 0 -1 -17];
[m n]=print(a)
y=eval(n);
figure(1);
plot(x,y,'LineWidth',3,'Marker','diamond','MarkerEdgeColor','k', ...
'MarkerFaceColor','y','MarkerSize',2,'Color','r');
title('多项式');
xlabel('X');
ylabel(m);
legend(m);
运行结果: