华氏温度与摄氏温度的转换;
c= input ('Plase input temperature in Celsius:');
f= (c*1.8)+32;
fprintf('huashiwendu =%g\n',f)
huashiwendu =68
%在matlab中fprintf为格式化输出,且括号内用单引号。
if语句的初步使用
num = input('qingshuruyigeshuzi :');
if num > 0
fprintf('Psitive\n');
else
fprintf('nagetive\n');
end
Psitive
% 在matlab中if else语句在结束时要加end。
% 用if语句比较两个数字的的大小
a = input('a =');
b = input('b =');
if a>b
fprintf('%g is greater\n',a);
else
if(a<b)
fprintf('%g is greater\n',b);
else
fprintf('equal');
end
end
10 is greater
判断三边能否组成三角形
a = input('Enter the value of a:');
b = input('Enter the value of b:');
c = input('Enter the value of c:');
if a+b<=c
fprintf('No\n');
elseif a+c<=b
fprintf('No\n');
elseif b+c<=a
fprintf('No\n');
else
fprintf('Yes\n');
end
No
判断由a、b、c为系数的一元二次方程有没有实数根
a = input('a=');
b = input('b=');
c = input('c=');
delta=b^2-4*a*c;
x1=(-b+sqrt(delta))/(2*a);
x2=(-b-sqrt(delta))/(2*a);
if delta<0
fprintf('No solution\n');
elseif delta==0
fprintf('1 solution\n');
fprintf('x1 = %g\n',x1);
else
fprintf('2 solution\n');
fprintf('x1 = %g\n',x1);
fprintf('x2 = %g\n',x2);
end
1 solution
x1 = NaN
display函数的使用
a=10;
disp(a);
10
fr1='apple';
fr2='banana';
fr3='orange';
disp([fr1,' ',fr2,' ',fr3]);
apple banana orange
%disp在使用时要在小括号内加入中括号,若要在三个变量之间加空格则需要用以上格式
让用户输入一个数字num,这个数字必须是1-100之间的数字,如果不在1-100之间,则输出wrong number,如果数字在这个范围内,则输出这个数字的平方。
num = input('Enter an integer between 1 and 100:');
if num>=1 && num<=100
disp(num^2);
else
disp('wrong number');
end
wrong number
while循环
t=1;
while t<5
disp(t);
t=t+1;
end
1
2
3
4
% while在应用时与if相同,都要在最后加上end。
辗转相除法
a = input ('a=');
b = input ('b=');
r=mod(a,b);
while r~=0
a=b;
b=r;
r=mod(a,b);
end
disp(b);
2
for循环
for i=1:5
disp(i);
end
1
2
3
4
5
%反向显示
for i = 5 : -1 : -5
disp(i);
end
5
4
3
2
1
0
-1
-2
-3
-4
-5
%1-100叠加
s=0;
for i=1:100
s=s+i;
end
disp(s);
5050
sum=0;
for i=1:100
sum=sum+(-1)^(i+1)*(1/i);
end
disp(sum);
0.6882
普通的线
X= -2*pi : 0.1 : 2*pi;
Y = sin(X);
plot(X,Y);
运动的线
X= -2*pi : 0.1 : 2*pi;
Y = sin(X);
h=plot(X,Y);
for i = 1 : 100
X = X+0.1;
Y = sin(X);
set(h, 'XData',X,'YData',Y);
drawnow;
end
拉伸压缩
t = -10*pi:0.1:10*pi
t = 1×629
-31.4159 -31.3159 -31.2159 -31.1159 -31.0159 -30.9159 -30.8159 ?
x=cos(t);
y=sin(t);
z=t;
j=plot3(x,y,z);
axis([-2,2,-2,2,-40,40]);
while true
for i=1:100
z=0.98*z;
set(j,'xData',x,'yData',y,'zData',z);
drawnow;
end
for i=1:100
z=z/0.98;
set(j,'Xata',x,'YData',y,'ZData',z);
drawnow;
end
end
时钟旋转
e = 0:pi/50:2*pi;
x=cos(e);
y=sin(e);
plot(x,y);
hold on;
axis equal;
linex=[0,1];
liney=[0,0];
hax=plot(linex,liney);
ta=0;
for i=1:1000
ta = ta+0.1;
linex(2)=cos(ta);
liney(2)=sin(ta);
set(hax,'XData',linex,'YData',liney);
drawnow;
end