编程结构
if elseif else
a = 10;
if mod(a,2)~=0 %也可以用rem,也是取余数
disp('a is a odd')
else
disp('a is a even')
end
switch case
switch expression
case condition1
command
case condition2
command
otherwise
command
end
input_num = -1;
switch input_num
case -1
disp('negative 1')
case 1
disp('objective')
otherwise
disp('not a number')
end
while
while expression
statement
end
n = 1
while prod(1:n) < 1e100 ##科学计数法,1乘以10的100次方,2e10就是2*10^10 prod(1 2 3 …… n)是求阶乘
n = n+1
end
%%---------------------
sum =0;
n = 1;
while n < 1000
n = n +1;
sum = sum +n;
end
disp(sum)
break和while一起出现,如果出现了break为true的条件,直接跳出跳出整个while,到end的地方
for
for variable = start:increment:end
commands
end
for i = 1:10
for j = 1:2:10
a(i,j) = 2^j+2^i;
end
end
disp(a)
pre-allocating
clear A
tic %开始计时
A = zeros(2000); %预宣告 pre-allocating
for ii = 1:2000
for jj = 1:2000
A(ii,jj)=ii+jj;
end
end
toc %结束计时
some tips
clear all close all clc ; 不在命令窗显示执行结果
… 太长的时候换行 ctrl + c 中断
函数
disp(freeBody(0,0,10));
function x = freeBody(x0,v0,t)
x = x0+v0.*t+1/2*9.8*t.*t;
end
----------------------------------------------
function [a,Force]=acc(v2,v1,t2,t1,m)
a = (v2-v1)./(t2-t1);
Force = m.*a
end
----------------------------------------------
function x = ftc(c)
c = input("输入摄氏度:");
while isempty(c)~=1
disp("对应的华氏度为");
temp = c*9/5+32;
disp(temp);
c = input("输入摄氏度:");
end
end
用==.*==的细节:如果输入的参数都是一个同样维度的矩阵,也就是多组数据,这样可以进行对应位置的数值计算,输出多组结果