MATLAB 结构化程序与自定义函数


前言

b站课程《MATLAB教程_台大郭彦甫(14课)》学习记录


第一部分

一、MATLAB Script 脚本

A file containing a series of MATLAB commands

Pretty much like a C/C++ program

Scripts need to be saved to a .m file before they can be run

二、Start A Script (.m) File

直接点击新建脚本即可

三、Script Editor

for i=1:10
    x=linspace(0,10,101);
    plot(x,sin(x+i));
    print(gcf,'-deps',strcat('plot',num2str(i),'.ps'));
end

执行方法:
1、点“运行”
2、按键盘上的“F5”
保存脚本注意点:
1、不可以数字开头
2、区分大小写

四、Script Flow

  1. Typically scripts run from the first line to the last
  2. Structured programming techniques (subroutine, loop, condition, etc) are applied to make the program looks neat
    结构化编程技术(子程序、循环、条件等)的应用使程序看起来整洁

五、编辑器部分功能介绍

1、“插入”后面的*fx*里面可供查找函数
2、某一行前面加“%”为注解,可以直接在编辑中找到
3、两个百分比符号分成一个“section”,即“节”,可以直接点击“运行节”就可以只运行一个section
4、进行debug时在某一行处标记一个断点,点运行会出现K,便是debug mode;鼠标移至某个变量处会出现他的值
5、智能缩进:先全选需要的程序,再按右键会出现智能缩进,会自动排版。

六、Flow Control

在这里插入图片描述

1、if elseif else

在这里插入图片描述
"elseif" and “else” are optional(可任意选择的)

a = 3;
if rem(a,2) == 0       【rem()为判断余数的函数)】
    disp('a is even')   【disp()为显示变量的值】【eve为偶数,old为奇数】
else
    disp('a is odd')
end

2、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

在这里插入图片描述

n = 1;
while prod(1:n) < 1e100  【prod()表示1*2*3*...*n】【1e100=1*10^100】
    n = n + 1;
end

Exercise

Use while loop to calculate the summation of the series 1+2+3+…+999

>> n = 1;
m = 0;
while n < 1000
    m = m + n;
    n = n + 1;
end
m
m =
      499500

4、for

在这里插入图片描述

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

若此时,将程序改为

>> for n = 1:2:10
    a(n) = 2^n;
end
disp(a)
  列 1 至 8
           2           4           8          16          32          64         128         256
  列 9 至 10
         512        1024

我们发现结果没变,我们就要注意在进行数值运算的时候,要及时消除变量的数值
所以应该先clear a;再进行程序运算

>> clear a
>> for n = 1:2:10
    a(n) = 2^n;
end
disp(a)
  列 1 至 7
     2     0     8     0    32     0   128
  列 8 至 9
     0   512

为什么会出现这么多零呢?因为你是对a这个数组都以2为步长来取,但是偶数的a(n)就没有数字赋予,只能变成0了。所以更好的方式应该是更改a(n)的公式进行计算。

>> clear a
>> for n=1:5
    a(n)=2^(2*n-1);
end
disp(a)
     2     8    32   128   512
  列 1 至 8
           2           4           8          16          32          64         128         256
  列 9 至 10
         512        1024

七、Relational (Logical) Operators 关系(逻辑)操作符

在这里插入图片描述
1为true
0为false

八、Pre-allocating Space to Variables 预先分配空间给变量

Pre-allocIn the previous example, we do not pre-allocate space to vector a rather than letting MATLAB resize it on every iteration
在前面的例子中,我们没有预先分配空间给向量a,而是让MATLAB在每次迭代时调整它的大小
Which method is faster?
在这里插入图片描述
B
B中的【A = zeros(2000,2000)为预先分配空间】

>> clear all;
tic
for ii = 1:2000
    for jj = 1:2000
        A(ii,jj) = ii + jj;
    end
end
toc
tic
B = zeros(2000, 2000);
for ii = 1:size(B,1)
    for jj = 1:size(B,2)
        B(ii,jj) = ii + jj;
    end
end
toc
历时 1.471070 秒。
历时 0.023827 秒。

Exercise

Use structured programming to:

  1. Copy entries in matrix A to matrix B
  2. Change the values in matrix B if their corresponding entries in matrix A is negative
    在这里插入图片描述
A = [0 -1 4;9 -14 25;-34 49 64];
B = zeros(3);
for i = 1:size(B,1)
    for j = 1:size(B,2)
        if A(i,j) >= 0
            B(i,j) = A(i,j);
        else
            B(i,j) = -A(i,j);
        end
    end
end
B

补充:size()的用法
若A为一个矩阵
size(A)则表示A的维数,行维数和列维数
size(A,1)则表示A的行维数
size(A,2)则表示A的列维数

九、break

Terminates the execution of for or while loops 终止for或while循环的执行

在这里插入图片描述
Used in iteration where convergence is not guaranteed 用于不能保证收敛的迭代中

十、Tips for Script Writing

  1. At the beginning of your script, use command
    (1). clear all to remove previous variables 清除变量
    (2). close all to close all figures 清除图形
    (3). clc to remove history in command window 清除命令行窗口中的内容
  2. Use semicolon ; at the end of commands to inhibit unwanted output
    使用分号在命令的末尾禁止不需要的输出
  3. Use ellipsis … to make scripts more readable:
    使用省略号使脚本更具可读性:
    一行内容太长,可以换两行输入,用省略号连接两行
>> A = [1 2 3 4 5 6;...
     6 5 4 3 2 1]
A =
     1     2     3     4     5     6
     6     5     4     3     2     1
  1. Press Ctrl+C to terminate the script before conclusion
    在结束前按Ctrl+C终止脚本

第二部分

一、Scripts vs. Functions

Scripts and functions are both .m files that contain MATLAB commands
脚本和函数都是包含MATLAB命令的.m文件
Functions are written when we need to perform routine
函数是在需要执行例程时编写的
fuction & script 最大的不同就是,script只用于个人所写,而function多了keyword,并且可以被其他script所引用
在这里插入图片描述

二、Content of MATLAB Built-in Functions MATLAB内置函数的内容

>> edit(which('mean.m'))

在这里插入图片描述

三、Some Observations

Keyword: function 关键词:函数
Function name matches the file name 函数名与文件名匹配
Directory: MATLAB needs to find the function 目录:MATLAB需要查找的函数
Input and output variables are optional 输入和输出变量是可选的
Local variables: dim and flag cannot be accessed 局部变量:dim和flag不能被访问

四、User Define Functions

在这里插入图片描述

>> edit (which('freebody.m'))
>> freebody(1,2,3
ans =
   51.1000

为什么用【.*】?
确保使用变量的不同数值时也可以一一对应相乘,所以不同变量相乘的时候需要用到.*

>> freebody([0 1],[0 1],[10 20])
ans =
         490        1981

五、 Functions with Multiple Inputs and Outputs

在这里插入图片描述

exercise

Write a function that asks for a temperature in degrees Fahrenheit
Compute the equivalent temperature in degrees Celsius
Show the converted temperature in degrees Celsius
The script should keep running until no number is provided to convert
You may want to use these functions: input, isempty, break, disp, num2str
写一个要求温度的函数,以华氏度为单位
用摄氏度计算当量温度
以摄氏度显示转换后的温度
脚本应该一直运行,直到没有提供可供转换的数字为止
你可能想要使用这些函数:
input:

x = input(prompt) 显示 prompt 中的文本并等待用户输入值后按 Return 键。
用户可以输入 pi/4 或 rand(3) 之类的表达式,并可以使用工作区中的变量。

isempty:

语法
TF = isempty(A)
说明
如果 A 为空,TF = isempty(A) 返回逻辑值 1 (true),否则返回逻辑值 0 (false)。
空数组、表或时间表有至少一个长度为 0 的维度,如 0×0 或 0×5。

break
disp
disp函数会直接将内容输出在Matlab命令窗口中
1.输出字符串:
Matlab命令窗口输入如下代码

disp(‘my test’)

Matlab命令窗口输出如下

my test

2.输出数字:
Matlab命令窗口输入如下代码

test=12;
disp(test)

Matlab命令窗口输出如下

3

3.同时输出字符串和数字:
Matlab命令窗口输入如下代码

test=3;
disp([‘my test=’,num2str(test)])

Matlab命令窗口输出如下

my test=3

————————————————
【版权声明:本段为CSDN博主「吴小风风」的原创文章中的部分内容,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sinat_34165087/article/details/79048423】
num2str
s = num2str(A) 将数值数组转换为表示数字的字符数组。输出格式取决于原始值的量级。num2str 对使用数值为绘图添加标签和标题非常有用。

s = num2str(pi)
s = 
'3.1416'
s = num2str(eps)
s = 
'2.2204e-16'

方法一:

function F2C
while(1)
    F = input('Temperature in F: ');
    t = isempty(F);
    if(t==1)
        break
    end
    C = (F-32) * 5/9;
    X = ['==> Temperature in C = ',num2str(C)];
    fprintf('\n')
    disp(X)
    fprintf('\n')
end
>> F2C
temperature in degrees Fahrenheit:[11 22 33]
temperature in degrees Celsius: -11.6667     -5.55556     0.555556
temperature in degrees Fahrenheit:
>> 

方法二:

function F2C()
while (1)
    F_degree = input('temperature in degrees Fahrenheit:');
    t = isempty(F_degree);
    if(t == 1)
        break
    end
    C_degree = (F_degree-32)*5/9;
    disp(['temperature in degrees Celsius: ',num2str(C_degree)])
end
>> F2C
Temperature in F: [11 22 33]
==> Temperature in C = -11.6667     -5.55556     0.555556
Temperature in F: 
>> 

方法三:

function F2C()
while 1
    F_degree = input('tempreature in Fahrenheit: ', 's');
    F_degree = str2num(F_degree);
    if isempty(F_degree)
        return
    end
    C_degree = (F_degree-32)*5/9;
    disp(['tempreature in Celsius: ' num2str(C_degree)])
end

————————————————
【版权声明:本代码为CSDN博主「ncepu_Chen」的原创代码,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ncepu_Chen/article/details/103047811】

>> F2C
tempreature in Fahrenheit: 11 22 33
tempreature in Celsius: -11.6667     -5.55556     0.555556
tempreature in Fahrenheit: 
>> 

六、 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 函数句柄

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

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

在这里插入图片描述


总结

继续加油吧。

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值