Matlab —— 结构化程式和自定函数

结构化程式和自定函数

  • **Script writing **
  • Structured programming
  • User-defined function

Script writing

##Flow Control

%%

if, elseif, else  // Execute statements if condition id true
for               // Execute statements specified number of times
switch, case, otherwise // Execute one of several groups of statements
try, catch        // Execute statements and catch resulting errors
while             // Repeat execution of statements while condition is true

%%
break             // Terminate execution of for or while loop
continue          // Pass control to next iteration of for or while loop
end               // Terminate block of code, or indicate last array index
pause             // Halt execution temporarily
return            // Return control to invoking function

Relational (Logical) Operators

OperatorMeaning
<Less than
<=Less than or equal to
>Greater than
==Equal to
~=Not equal to
&&And

if elseif else

if condition1 
    statement1
elseif condition2
    statement2
else
    statement3
end

"elseif" and "else" are optional

示例

a = 3;
if rem(a, 2) == 0    %rem 意为 求余
    disp('a is even')
else 
    disp('a is odd')
end

switch

switch expression 
case value1
    statement1
case value2
    statement2
...
otherwise
    statement
end
  • switch 与 if 的不同在于,switch 判断的是一个具体的数值,而 if 判断的是 true or false

示例

input_num = 1;
switch input_num
    case -1
        disp('negetive 1');
    case 0
        disp('zero');
    case 1
        disp('positive 1');
    otherwise
        disp('other value');
end

while

while expression
    statement
end

while 一直执行 statement 直到值为 false

示例

n = 1;
while prod(1:n) < 1e100
    n = n + 1;
end

prod 意为 将数组元素连乘
1:n 意为 [1, 2, 3, 4, ..., n]的向量
prod(1:n) n的阶乘
1e100 意为 1 * 10^100

for

for variable = start : increment : end
        commands
end

示例

for n = 1:2:10
    a((n + 1)/2) = 2^n;
end
disp(a)

若把 (n + 1)/2 写作 n,结果是什么?
如果更改 a(n) 里的 n 时,没有对 a 进行 clear,结果是什么?

Pre-allocating Spacing to Variables

%%
tic
for ii = 1:2000
    for jj = 1:2000
        A(ii,jj) = ii + jj;
    end
end
toc

%%
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

###Tip for Script Writing

  • At the beginning of your script , use command
: clear all to remove previous variables
close all to close all figures
  • Use semicolon ; at the end of commands to inhibit unwanted output
  • Use ellipsis … to make scripts more readable:
A = [1 2 3 4 5 6; ...
 6 5 4 3 2 1 ];   // 换行号 
  • Press ctrl + C to terminate the script before conclusion

Functions

Content of Matlab Built-in Functions

  • Keyword : function
  • Unction name matches the file name
  • Directory: MATLAB needs to find the function
  • Input and output variables are optional
  • Local variables : dim and flag cannot be accessed

User Define Functions

  • Write a function that calculate the displacement of free falling for given initial displacement x0 ,initial velocity v0, and duration of falling t:
    x = x0 + v0t + 1/2 gt^2
function x = freebody(x0,v0,t)
% calculation of free falling
% x0:initial displacement in m
% v0:iniyial velocity in m/sec
% t:the elspsed time in sec
% x:the depth of falling in m
x = x0 + v0.*t + 1/2*9.8*t.*t;
% 注意是点乘,而非叉乘

Summary

function : the keyword
x : output
freebody : function name(else filename)
x0, v0, t : input
annotation : command
code

Function with Multiple Inputs and Outputs

  • The acceleration of a particle and the force acting on it are as follows:
    : a = (v2-v1)/(t2-t1)
    : F = m*a
function [a F] = acc(v2,v1,t2,t1,m)
a = (v2-v1)./(t2-t1);
F = m.*a;

Function Default Variables

inputname Variable name of function input
mfilename File name of currently running function
nargin Number of function input arguments
nargout Number of function outputarguments
varargin Variable length input argument list
varargout Variable length output argument list

Function Handles

  • A way to creat anonymous functions,i.e.,one line expression functions that do not have to be defined in .m files
  • 类似指针pointer
f = @(x) exp(-2*x);
x = 0:0.1:2;
plot(x,f(x));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值