我是看的B站上灯神的视频学习的matlab,由于已经学过好几种语言了,所以并没有觉得特别难懂,但是有些比较明显的地方,我还是放在下面,方便自己以后回忆。
x ~= 0 %x不等于0
mod(172,56) %取模
x=-3:0.1:3 %从-3到3,每次增长0.1
x=x.*x %x的平方
x=x.^3 %x的三次方
求和
x=input('enter a x:');
y=input('enter a y:');
fprintf('%g + %g = %g\n',x,y,x+y);
判断
num = input('please enter a number:');
if num > 0
fprintf('positive\n');
elseif num < 0
fprintf('negative\n');
else
sprintf('num=0\n');
end
是否能构成三角形
a = input('enter a value of a:');
b = input('enter a value of b:');
c = input('enter a value of c:');
if (a + b >c) &&( b + c > a)&&(a + c > b)
fprintf('Yes\n')
else
fprintf('No\n')
end
判断二次方程是否有解
a=input('a=');
b=input('b=');
c=input('c=');
delta = b^2 - 4 *a*c;
if delta >0
fprintf('2 solutions\n');
x1= (-b + sqrt(delta))/(2*a);
x2=(-b - sqrt(delta))/(2*a);
fprintf('x1=%f\n',x1);
fprintf('x2=%f\n',x2);
elseif delta==0
fprintf('1 solution\n');
x1=-b /(2*a);
fprintf('x1=%f\n',x1)
else
fprintf('no solution\n');
end
循环
v =[5 7 9 10 12 32];
s= 0;
for i = v
s=s+i;
end
disp(s)
disp(sum(v))
函数
function result=mysum(a,b)
s = 0;
for i = a:b
s =s+i;
end
result = s;
end
动画
X=-2*pi:0.1:2*pi;
Y = sin(X);
h = plot(X,Y);
while true
X = X+0.1;
Y = sin(X);
set(h,'XData',X,'YData',Y)
drawnow;
end
约数个数
function result = count_factor( n )
count=0;
for i=1:n;
if mod(n,i)==0
count=count+1;
end
end
result=count;
end
是否为素数
function result =is_prime( n)
count=count_factor(n);
if count==2
result=1;
else
result=0;
end
end
列出1-1000之间的所有质数
for i=1:1000
if is_prime(i)==1
disp(i)
end
end
动画
theta = -10*pi:0.1:10*pi;
X = cos(theta);
Y = sin(theta);
Z = theta;
h = plot3(X,Y,Z);
while true
for i = 1:100
Z=0.98*Z;
set(h,'XData',X,'YData',Y,'ZData',Z);
drawnow;
end
for i = 1:100
Z=Z/0.98;
set(h,'XData',X,'YData',Y,'ZData',Z);
drawnow;
end
end
动画
t=0:pi/50:2*pi;
X=cos(t);
Y = sin(t);
plot(X,Y);
axis euqal;
动画
t=0:pi/50:2*pi;
X=cos(t);
Y = sin(t);
plot(X,Y);
hold on;
lineX = [0,1];
lineY= [0,0];
h = plot(lineX,lineY);
theta=0;
while true
theta = theta + 0.05;
lineX(2)=cos(theta);
lineY(2)=sin(theta);
set(h,'XData',lineX,'YData',lineY);
drawnow;
end
动画
X=-10:0.4:10;
Y=-10:0.4:10;
[XX,YY]=meshgrid(X,Y);
ZZ=sin(XX)+cos(YY);
h=surf(XX,YY,ZZ);
% axis([-10,10,-10,10,-5,5]);
while true
for i=1:100
ZZ=0.97*ZZ;
set(h,'XData',XX,'YData',YY,'ZData',ZZ);
drawnow;
end
for i=1:100
ZZ=ZZ/0.97;
set(h,'XData',XX,'YData',YY,'ZData',ZZ);
drawnow;
end
end