Structure Programming
Logical Operators
1. if语句
%% if elseif else
a = 3;
if rem(a,2) == 0
disp('a is even.');
else
disp('a is odd.');
end
2. switch语句
%% switch
input_num = 1;
switch input_num
case -1
disp('negative 1');
case 0
disp('zero');
case 1
disp('positive 1');
otherwise
disp('other value');
end
3. while语句
%% while
n = 1;
while prod(1:n) < 1e100 %prod 连乘
n = n+1;
end
%% Exercise
sum = 0;
i = 0;
while i < 999
i = i + 1;
sum = sum + i;
end
4. for语句
%% for
for x = 1:10
a(x) = 2^x;
end
disp(a);
for y = 1:2:10
b(y) = 2^y;
end
disp(b);
for z = 1:2:10
c(z) = 2^z;
disp(c(z));
end
5. 预分配内存
%% pre-allocating space
%% program A
tic
for ii = 1:2000
for jj = 1:2000
A(ii,jj) = ii + jj;
end
end
toc
%% program B
tic
A = zeros(2000,2000);
for ii = 1:size(A,1)
for jj = 1:size(A,2)
A(ii,jj) = ii + jj;
end
end
toc
Exercise
%% Exercise
clear all;clc;
A = [0 -1 4; 9 -14 25;-34 49 64];
B = zeros(3,3);
for ii = 1:size(A,1)
for jj = 1:size(A,2)
B(ii,jj) = abs(A(ii,jj));
end
end
disp(B);
6.break
%% break
clear all;clc;
x = 2; k = 0; error = inf;
error_threshold = 1e-32;
while error > error_threshold
if k > 100
break
end
x = x - sin(x)/cos(x);
error = abs(x-pi);
k = k + 1;
end
小技巧
1. clear all、close all、clc
2.使用分号(;)
3.使用换行号(...)
Function
自定函数
%% user define functions
function x = freebody(x0,v0,t)
% calculation of free falling
% x0: initial displacement i m
% v0: initial velocity in m/sec
% t: the elapsed time in sec
% x: the depth of falling in m
x = x0 + v0.*t + 1/2*9.8*t.*t; % t采用点乘,让多组数据可同时计算
>> freebody(0,0,10)
ans =
490
>> freebody([0 1],[0 1],[10 20])
ans =
490 1981
%% functions with multiple inputs and outputs
function [a,F] = acc(v2,v1,t2,t1,m)
a = (v2 - v1)./(t2 - t1);
F = m.*a;
>> [Acc Force] = acc(20,10,5,4,1)
Acc =
10
Force =
10
Exercise
%% Fahrenheit degrees to Celsius degrees
function F2C
while 1
% 这是一个无限循环,它会一直执行下去,
% 直到遇到 break 语句才会退出循环。
F_degree = input('Tempreature in F:','s');
% 这行代码从用户处获取输入,要求用户输入一个华氏度的温度值,
% 并将其存储在 F_degree 变量中。'Tempreature in F:' 是输入提示文本。
F_degree = str2num(F_degree);
% 这行代码将用户输入的温度值(字符串类型)转换为数值类型,
% 并将结果存储回 F_degree 变量中。
if isempty(F_degree)
break
end
%这个条件语句检查 F_degree 是否为空。
% 如果用户没有输入任何内容,那么 F_degree 将为空,这时会执行 break 语句,退出循环。
C_degree = (F_degree - 32).*5/9;
disp(['Tempreature in Celsius:' num2str(C_degree)])
% 这行代码使用 disp 函数在命令窗口中显示转换后的摄氏度值。
% 它将摄氏度值转换为字符串,然后与前缀文本 'Tempreature in Celsius:' 连接起来进行显示。
end