實驗五 函數(shù)文件
第一題
function?y=mat1(x)????%建立函數(shù)文件mat1.m
y=[exp(x),log(x),sin(x),cos(x)];
%在命令窗口調用上述函數(shù)文件:
y=mat1(1+i)
%第二題程序一
function?[a,b,N,M]=shiyanwu2(m,n,t)
A=[m*cos(t*pi/180),-m,-sin(t*pi/180),0;m*sin(t*pi/180),0,cos(t*pi/180),0;0,n,-sin(t*pi/180),0;0,0,-cos(t*pi/180),1];
B=[0,9.8*m,0,9.8*n];
C=inv(A)*B';
a=C(1);
b=C(2);
N=C(3);
M=C(4);
%在命令窗口調用該函數(shù)文件:
m1=input('m1=');
m2=input('m2=');
theta=input('theta=');
[a1,a2,N1,N2]=shiyanwu2(m1,m2,theta)
%第二題程序二
function?X=mat2(m1,m2,t)
g=9.8;
A=[m1*cos(t*pi/180),-m1,-sin(t*pi/180),0;m1*sin(t*pi/180),0,cos(t*pi/180),0;0,m2,-sin(t*pi/180),0;0,0,-cos(t*pi/180),1];
B=[0;m1*g;0;m2*g];
X=inv(A)*B;
%在命令窗口調用該函數(shù)文件:
X=mat2(1,1,60)
%第三題
function?flag=mat3(x)
flag=1;
for?i=2:sqrt(x)
if?rem(x,i)==0
????flag=0;
????break;
end
end
%在命令窗口調用該函數(shù)文件:
for?i=10:99
j=10*rem(i,10)+fix(i/10);
if?mat3(i)&mat3(j)
???disp(i)
end
end
%第四題
function?y=fx(x)
y=1./((x-2).^2+0.1)+1./((x-3).^4+0.01);
%在命令窗口調用該函數(shù)文件:
y=fx(2)
a=[1,2;3,4];
y=fx(a)
%第五題
%(1)
function?f1=mat5(n)
f1=n+10*log(n*n+5);
%在命令窗口中調用該函數(shù)文件:
y=mat5(40)/(mat5(30)+mat5(20))
%(2)方法一
function?f2=mat6(n)
f2=0;
for?i=1:n
????f2=f2+i*(i+1);
end
%在命令窗口中調用該函數(shù)文件如:
y=mat6(40)/(mat6(30)+mat6(20))
%(2)方法二
function?f2=mat7(n)
i=1:n;
m=i.*(i+1);
f2=sum(m);
end
%在命令窗口中調用該函數(shù)文件如:
y=mat7(40)/(mat7(30)+mat7(20))
實驗六 高層繪圖操作
第一題:
x=linspace(0,2*pi,101);
y=(0.5+3*sin(x)./(1+x.^2)).*cos(x);
plot(x,y)
%第二題:
%(1)
x=linspace(-2*pi,2*pi,100);
y1=x.^2;
y2=cos(2*x);
y3=y1.*y2;
plot(x,y1,'b-',x,y2,'r:',x,y3,'y--');
text(4,16,'\leftarrow?y1=x^2');
text(6*pi/4,-1,'\downarrow?y2=cos(2*x)');
text(-1.5*pi,-2.25*pi*pi,'\uparrow?y3=y1*y2');
%(2)
x=linspace(-2*pi,2*pi,100);
y1=x.^2;
y2=cos(2*x);
y3=y1.*y2;
subplot(1,3,1);%分區(qū)
plot(x,y1);
title('y1=x^2');%設置標題
subplot(1,3,2);
plot(x,y2);
title('y2=cos(2*x)');
subplot(1,3,3);
plot(x,y3);
title('y3=x^2*cos(2*x)');
%(3)
x=linspace(-2*pi,2*pi,20);
y1=x.^2;
subplot(2,2,1);%分區(qū)
bar(x,y1);
title('y1=x^2的條形圖');%設置標題
subplot(2,2,2);
stairs(x,y1);
title('y1=x^2的階梯圖');
subplot(2,2,3);
stem(x,y1);
title('y1=x^2的桿圖');
subplot(2,2,4);
fill(x,y1,'r');%如果少了'r'則會出錯
title('y1=x^2的填充圖');
%其他的函數(shù)照樣做。
%第三題
x=-5:0.01:5;
y=[];%起始設y為空向量
for?x0=x
if?x0<=0??%不能寫成x0=<0
y=[y,(x0+sqrt(pi))/exp(2)];????%將x對應的函數(shù)值放到y中
else
y=[y,0.5*log(x0+sqrt(1+x0^2))];
end
end
plot(x,y)
%第四題:
a=input('a=');
b=input('b=');
n=input('n=');
t=-2*pi:0.01:2*pi;
r=a*sin(b+n*t);
polar(t,r)
%第五題
x=linspace(-5,5,21);
y=linspace(0,10,31);
[x,y]=meshgrid(x,y);%在[-5,5]*[0,10]的范圍內生成網(wǎng)格坐標
z=cos(x).*cos(y).*exp(-sqrt(x.^2+y.^2)/4);
subplot(2,1,1);
surf(x,y,z);
subplot(2,1,2);
contour3(x,y,z,50);%其中50為高度
的等級數(shù),越大越密
%第六題
ezsurf('cos(s)*cos(t)','cos(s)*sin(t)','sin(s)',[0,0.5*pi,0,1.5*pi]);?%利用ezsurf隱函數(shù)
shading?interp??%進行插值著色處理