matlab ——结构化程式与自定义函数
script writing
打开new script:
某一句变注解:前面加%
一大段变注解:选中后右键"comment" ;
取消注解 :右键"uncomment"
划区块: %%
执行区块: run section
执行全部 :run
自动缩排 :选中后右键"smart indent"
Structured programming
relational (logical) operators: < <= > >= == ~=(not equal to) &&(and) ||(or)
structure programming:
if elseif else end
switch
while
for
pre-allocating space to variables 预宣告可以提升运行速度
tips for script writing
(1)clear all : to remove previous variables
(2)close all : to close all figures
(3)use semicolon ; at the end of commands to inhibit unwanted output 语句末尾使用分号不输出
(4)use ellipsis… to make scripts more readable:
A=[1 2 3 4 5 6 ;…
6 5 4 3 2 1 ]; 语句过长用省略号换行
(5)press Ctrl+C to terminate the script before conclusion 及时终止程序运行
scripts vs function
script 需要打开、编程,function直接呼叫调用即可
function示例:
function x = freebody(x0,v0,t)
%calculation of free falling
%x0 : initial displacement in m
%v0 : initial velocity in m/sec
%t : the escaped time in see
%x : the depth of falling in m
x= x0 + v0.*t+1/2*9.8*t.*t;
%注意是点乘而非叉乘,适用于矩阵
User-defined function
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 output arguments 输出参数个数
varargin : variable length input argument list 输入参数的变量长度
varargout : variable length output argument list 输出参数的变量长度
function handle :类似于指针