Matlab学习(台大郭彦甫)第3节-结构化程式和自定义函数

第3节 结构化程式和自定义函数

3.1 Matlab Script(脚本)

  • A file containing a series of MATLAB commands(一个包含系列指令的文件)
  • Pretty much like a C/C++ program(与C/C++程式语言相似)
  • Scripts need to be save to a .m file before they can run(在执行前需要保存为脚本文件)

简单的说,就是创建一个后缀名为 .m 的脚本文件,该文件内包含一系列指令,这些编程类似于C语言或者C++等高级语言。

3.2 Script FLow(脚本执行流)

  • Typically scripts run from the first line to the last(通常脚本从第一行执行到最后一行)
  • Structured programming techniques(subroutine,loop,condition,etc)are applied to make the program looks neat(应用结构化编程技术可以让程序看起来更简洁,如子程序、循环、条件等)
  • Flow Control(执行流控制)

3.2.1 Flow Control(执行流控制)

在这里插入图片描述
(1) ifelseifelse:Execute statements if condition is true(条件为真时执行语句)

(2) for:Execute statements specified number of times(执行指定次数的语句)

(3) switchcaseotherwise:Execute one of several groups of statements(执行几组语句之一)

(4) trycatch:Execute statements and catch resulting errors(执行语句并捕获产生的错误)

(5) while:Repeat execution of statements while condition is true(条件为真时重复执行语句)

(6) break:Terminate execution of for or while loop(终止for或while循环的执行)

(7) continue:Pass control to next iteration of for or while loop(将控制传递到for或while循环的下一次迭代)

(8) end:Terminate block of code,or indicate last array index(终止代码块,或指示最后一个数组索引)

(9) pause:Halt execution temporarily(暂时停止执行)

(10) return:Return control to invoking function(返回控件值到调用的函数)

3.2.2 Relational(Logical)Operators(关系/逻辑运算符)

在这里插入图片描述

3.2.3 几个常见的执行流控制语句(重点掌握)

  • if elseif else 语句

语法为:
在这里插入图片描述
注意:其中的elseif 和 else 不是必须的,可以不用这两个。

例子:

clear;
clc;
a=4;
if rem(a,2)==0
    disp('a is even');
else
    disp('a is odd');
end

注意:
(1)r=rem(a,b)返回a除以b后的余数,其中a是被除数,b是除数。这里rem(a,2)==0,是判断a/2是否有余数,即a是否能是2的倍数。
(2)disp()函数,可以显示变量的值,这个变量也可以是字符串。

  • switch 语句

语法为:
在这里插入图片描述
例子:

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

这里通过判断 input_num的值,
如果input_num=-1,则输出negative;
如果input_num=0,则输出zero;
如果input_num=1,则输出positive;
如果input_num为其他数值,则输出other value.

  • while语句

语法为:
在这里插入图片描述
例子:
n!<1x10^100,找出满足该不等式的最大n值

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

注意:prod()函数,可以用于计算数组元素的乘积。题中,prod(1:n)就代表,从1到n的整数的乘积,就是n!

练习题:
利用语句实现:1+2+3+…+998+999=

clear;
clc;
n=1;
sum=0;
while n<1000
    sum=sum+n;
    n=n+1;
end
disp(sum);
  • for语句
    语法为:
    在这里插入图片描述

例题:

clear;
clc;
i=1;
for n=1:2:10
    a(i)=2^n;
    i=i+1;
end
disp(a);

结果是生成数组,数组的元素分别为:2^1 ,2^3 ,2^5 ,2^7 ,2^9

例题:
在这里插入图片描述
上面A、B两个部分的代码结果相同,要比较哪一个的运行速度更加的快。

注意:
tic
.
.
toc
是用来判断中间代码的运算时间的。
结果:A=时间已过 3.638619 秒;B=时间已过 0.025104 秒
分析:很明显,B代码运行更加的快,因为B代码中率先对A数组进行了一个预定义,后面的操作只是对其中元素的赋值;而A代码是在一边定义数组A,一边对这个数组进行填充,就相当于A数组中有多少个元素,就对其定义了多少次,故更加耗时。
推荐使用B代码中预先定义的方法。

练习:
在这里插入图片描述
将A矩阵中的负数元素取相反数,并赋值给矩阵B。

clear;
clc;
A=[0 -1 4;9 -14 25;-34 49 64];
B=zeros(3,3);
for i=1:9
    if A(i)<0
        B(i)=-A(i);
    else
        B(i)=A(i);
    end
end
disp(B);
  • break语句
    用该语句跳出循环:
    例题:
clear;
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

3.3 Functions(函数)

利用命令行:edit(which(‘mean.m’))------------用于打开‘mean’的代码

3.3.1 函数的主要结构

可以观察到函数的主要结构:
在这里插入图片描述
(1)关键字:function
(2)输出
(3)函数名
(4)输入
(5)注释
(6)函数体代码

  • 自定义函数的例题
    1)定义一个自由落体的函数
    在这里插入图片描述
    分析:输入有:x0,v0,t ;输出为x
    代码:
function x = freebody(x0,v0,t)
    x=x0+v0.*t+0.5*9.8.*t.*t;
end

在这里插入图片描述
注意:这里用的 . * ,即用的点乘。即可以实现,当输入为数组时,输出仍然是数组
在这里插入图片描述
2)定义一个计算加速度和牛顿力的函数
在这里插入图片描述
分析:这里输入有v2,v1,t2,t1,m;输出有a,F

代码:

function [a,F] = acc(v2,v1,t2,t1,m)
    a=(v2-v1)./(t2-t1);
    F=m.*a;
end

在这里插入图片描述
3)将华氏温度转换为摄氏温度
在这里插入图片描述
代码:

function  FtoC
    while 1
        F=input('Temperature in F :');
        if isempty(F)
            break;
        else
            C=(F-32).*5/9;
            disp(['===> Temperature in C= ',num2str(C)]);
        end
    end
end

注意:

  • F=input()函数,请求用户输入。运行该指令时,输入一个数,就会将其赋值给F
  • X=isempty()函数,确定数组是否为空。这个函数会判断括号内是否为空,如果是,则返回1给X,如果不是空,则返回0给X
  • num2str()函数,将数字转换为字符数组
  • 可以看到,在关键字function后面,可以不用接上输入和输出,只写一个函数名也可以。

在这里插入图片描述
该函数会一直执行,知道按下 Ctrl+C才会结束。

3.3.2 Function Default Variables(函数默认变量)

(1) inputname :Variable name of function input(函数输入的变量名)

(2) mfilename :File name of currently running function(当前运行函数的文件名)

(3) nargin :Number of function input arguments(函数输入参数数目)

(4) nargout :Number of function output arguments(函数输出参数数目)

(5) varargin :Variable length input argument list(可变长度输入参数列表)

(6) varargout :Variable length output argument list(可变长度输出参数列表)

3.3.3 Function Handles(函数句柄)

A way to create anonymous functions,i.e.,one line expression functions that do not have to be defined in .m files(一种创建匿名函数的方法,即不必在.m文件中定义的单行表达式函数)
示例:

clear;
clc;
f=@(x) exp(-2*x);
x=0:0.1:2;
plot(x,f(x));

在这里插入图片描述
分析:
代码:f=@(x) exp(-2x);
其中 f 代表函数名;@(x)括号中代表自变量;exp(-2
x)函数体代码

参考这位博主写的:博主原文戳这里哦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值