
function y=fun(x)
if x<0&&x~=-3
y=x.^2+x-6;
elseif x>=0&&x<5&&x~=2&&x~=3
y=x.^2-5.*x+6;
else
y=x.^2-x-1;
end
end
----------------------------------
A=[-5 -3 1 2 2.5 3 5];
for i=1:6
y(i)=fun(A(i)) ;
end
y
y =
14.0000 11.0000 2.0000 1.0000 -0.2500 5.0000
A=[-5 -3 1 2 2.5 3 5];
for i=1:6
y(i)=fun(A(i)) ;
end
y

function pei =fun(x)
sum=0;
for i=1:x
sum=sum+1/i^2;
pei=sqrt(6*sum);
end
pei
end
----------------------------------
fun(10)
ans =
3.0494
>> fun(100)
ans =
3.1321
>> fun(10000)
ans =
3.1415
----------------------------------
方法2
n1=1:100;
pai=sqrt(6*sum(1./(n1.*n1)))
n2=1:1000;
pai=sqrt(6*sum(1./(n2.*n2)))
n3=1:10000;
pai=sqrt(6*sum(1./(n3.*n3)))
结果:
n=100 =3.1321
n=1000 =3.1406
n=10000 =3.1415
function pei =fun(a,b)
x(1)=1;
if a<=0||b<=0
disp(‘error!‘);
end
for i=1:500;
x(i+1)=a/(x(i)+b);
if abs(x(i+1)-x(i))<=0.00001
break;
end
end
x(i)
r1=1/2*(-b+sqrt(b^2+4*a))
r2=1/2*(-b-sqrt(b^2+4*a))
end
--------------------------------------------
fun(1,1)
ans =
0.6180
r1 =
0.6180
r2 =
-1.6180
>> fun(8,3)
ans =
1.7016
r1 =
1.7016
r2 =
-4.7016
>> fun(10,0.11)
ans =
3.1078
r1 =
3.1078
r2 =
-3.2178
原文:https://www.cnblogs.com/xxfx/p/12458277.html