Matlab循环赋值问题

来源:百度知道 编辑:UC知道 时间:2024/06/14 04:07:52
x=[2 3 4 5 7 8 10 11 14 15 16 18 19];
y=[106.42 108.26 109.58 109.5 110 109.93 110.49 110.59 110.6 110.9 110.76 111 111.2];
Xmin=min(x);
Xmax=max(x);
for n=3:5
v(n)=polyfit(x,y,n);
x3(n)=Xmin:0.5:Xmax;
y3(n)=polyval(v(n),x3(n));
text=['第',n,'次模拟函数为:'];
disp(text);
disp(poly2str1(v(n)));
end
在循环赋值的时候,出现了一个左右不匹配问题
In an assignment A(I) = B, the number of elements in B and In an assignment A(I) = B, the number of elements in B and.

clear;clc;
x=[2 3 4 5 7 8 10 11 14 15 16 18 19];
y=[106.42 108.26 109.58 109.5 110 109.93 110.49 110.59 110.6 110.9 110.76 111 111.2];
x3=min(x):0.1:max(x);%可以放在循环外
%v=zeros(3,6);没有必要,需要的话可以,v=[];
for n=1:3
v(n,1:n+3)=polyfit(x,y,n+2);
y3(:,n)=polyval(v(n,1:n+3),x3);
text=strcat(num2str(n+2),'次多项式模拟函数为');
disp(text);
disp(poly2str(v(n,1:n+3),'x'));
end
%用多项式拟合一般效果都不好,用分式拟合效果好
fun=@(a,t) (a(1)*t.^2 + a(2)*t + a(3))./ (t + a(4))
a0=[0.1 100 -100 -1];
a=nlinfit(x,y,fun,a0)
yf=fun(a,x3);
plot(x,y,'o',x3,y3,x3,yf,'*')

结果:
3次多项式模拟函数为
0.0032566 x^3 - 0.12242 x^2 + 1.5113 x + 104.4824
4次多项式模拟函数为
-0.00048007 x^4 + 0.023554 x^3 - 0.40963 x^2 + 3.0473 x + 102.0444
5次多项式模拟函数为
9.6416e-005 x^5 - 0.0054588 x^4 + 0.11758 x^3 - 1.2012 x^2 + 5.9223 x

+ 98.5719

fun =

@(a,t)(a