当前位置:网站首页>Matlab02: structured programming and function definition "suggestions collection"
Matlab02: structured programming and function definition "suggestions collection"
2022-07-29 00:44:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
pdf Download address of version notes : MATLAB02_ Structured programming and function definition ( Access password :3834)
MATLAB02: Structured programming and function definition
- Structured programming
- function
The best way to learn a technology is to read official documents , You can see MATLAB Official documents
Structured programming
Process control statements and logical operators
Same as most programming languages ,MATLAB There are the following flow control statements :
Flow control statement | effect |
|---|---|
if, elseif, else | if if The statement is true , Execute clause |
switch, case, otherwise | according to switch The content of the statement determines which clause to execute |
while | Repeat the clause until while The condition in is false |
for | Execute the clause a fixed number of times |
try, catch | Execute clauses and catch exceptions during execution |
break | Out of the loop |
continue | Go directly to the next cycle |
end | End clause |
pause | Suspend program |
return | Return to the calling function |
All the above loops and conditional statements should end with
endclosed .
MATLAB There are also the following logical operators :
Operator | significance |
|---|---|
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
== | be equal to |
~= | It's not equal to |
&& | And |
|| | or |
&&and||The operator supports the function of logical short circuit .
Example of process control statement
The following is a demonstration of each process control statement :
Try to pre allocate memory space when using circular statements
If the memory space required by a variable is a predictable fixed value , We should try to allocate memory space for it in advance .
Take the following two procedures as examples , Demonstrate this :
You can see , Program one takes longer than program two . This is because : For program one , There is no pre variable A Allocate memory , So whenever A When the shape of the changes , All need to be re A Allocate memory address , It takes more time .
Problems that should be paid attention to when writing scripts
Add a statement at the beginning of the script to empty the workspace
At the beginning of each script , The following statement should be added , Clear the workspace cache and traces of previous program runs :
clear all % Clear variables in the workspace memory
close all % Close the image drawn by the program before
clc % Clear the output of the program on the terminal before Semicolons should be added after operations and assignment statements ; Suppress output
Semicolons should be added to all operations and assignment statements ; Suppress output , If you need to output a variable to the terminal , It should be called disp Method .
Use ellipsis ... Splice multiple lines
stay MATLAB in , Ellipsis ... You can splice multiple lines of statements into one line , Using this statement flexibly can improve the readability of the code .
annPoints_sampled = annPoints(annPoints(:,1)>x1 & ...
annPoints(:,1) < x2 & ...
annPoints(:,2) > y1 & ...
annPoints(:,2) < y2);function
Similar to other languages ,MATLAB You can also define functions . Similar to scripts , Functions can be stored Function name .m In file , It can also be defined in memory in the form of a function handle .
See built-in functions
We can use which Command to view the location of the built-in function source code file , And edit Command can be combined to view the source code of built-in functions .
Run the following statement to open MATLAB Built in mean Function source file :
edit(which('mean.m')) You can see in the editor mean The source code of the function is as follows :
With Function name .m File form definition function
stay MATLAB The format of the function defined in the file is as follows :
function [ Output variable name ] = Function name ( Enter variable name )
% Documentation for functions
function code functionIt's a keyword , Declare that what is saved in this file is a function .The input variableandOutput variablesnonessential , Functions can have no input variables , You can also have no output variables .Function nameShould and.mSame file name , And does not contain special characters ( It's better not to have Chinese ).
MATLAB Built in function parameters
stay MATLAB in , Some built-in function parameters are as follows :
Function parameter | significance |
|---|---|
imputname | Enter a list of variable names |
mfilename | Function source code file name |
nargin | Enter the number of variables |
nargout | Number of output variables |
varargin | Variable length input parameter list |
varargout | Variable length output parameter list |
MATLAB It does not provide the syntax of specifying default parameter values and function overloading in other high-level languages , But use the built-in function parameters mentioned above flexibly , You can specify the default parameter value and method overloading to a certain extent :
function [volume]=pillar(Do,Di,height)
if nargin==2,
height=1;
end
volume=abs(Do.^2-Di.^2).*height*pi/4;MATLAB Function definition example 1
The following program is used to calculate the displacement of a free falling body : x = x 0 + v 0 t + 1 2 g t 2 x = x_0 + v_0 t + \frac{1}{2} g t^2 x=x0+v0t+21gt2
function x = freebody(x0,v0,t)
% calculation of free falling
% x0: initial displacement in 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; This function demonstrates a MATLAB Programming skills : Try to use .* Instead of *, Because the former is not only for parameters t Scalar case is available , Also for variables t In the case of vectors or matrices .
freebody(0, 0, 2) % obtain 19.6000
freebody(0, 0, [0 1 2 3]) % obtain [0 4.9000 19.6000 44.1000]
freebody(0, 0, [0 1; 2 3]) % obtain [0 4.9000; 19.6000 44.1000]MATLAB Function definition example 2
The following function realizes the conversion from Fahrenheit temperature to Celsius temperature , This function can identify the number of input samples to be converted , When the number of samples to be converted is 0 when , Exit function .
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( Need to press Ctrl+C Exit procedure )
Define a function in the form of a function handle
We can also define functions in the form of function handles , This is closer to the mathematical definition of function , The syntax is as follows :
Function handle = @( The input variable ) Output variables You can call this method directly through the function handle .
f = @(x) exp(-2*x);
x = 0:0.1:2;
plot(x, f(x));pdf Download address of version notes : MATLAB02_ Structured programming and function definition ( Access password :3834)
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/128968.html Link to the original text :https://javaforall.cn
边栏推荐
- Breadth first search (BFS) and its matlab code
- PTA (daily question) 7-73 turning triangle
- The 30th day of question brushing
- 直流无刷电机控制器(换电机霍尔收费多少)
- Execute immediate simple sample set (DML)
- Software designer afternoon question
- Brief introduction to compressed sensing
- 多线程顺序运行的几种方法,面试可以随便问
- Shell编程规范与变量
- Oracle实例无法启动的问题如何解决
猜你喜欢

2022DASCTF7月赋能赛(复现)

Idea connection database

17.机器学习系统的设计

Teach you how to install latex (nanny level tutorial)

时间序列统计分析

面试被问到了String相关的几道题,你能答上来吗?

Dynamic programming (V)

Some operations of Ubuntu remote server configuration database (unable to locate package MySQL server, steps of installing mysql, unable to enter password when logging in MySQL)

Recursion / backtracking (Part 2)

Oracle实例无法启动的问题如何解决
随机推荐
Introduction and solution of common security vulnerabilities in Web System SQL injection
Summary: the difference between pod and container
Software designer afternoon question
乱打日志的男孩运气怎么样我不知道,加班肯定很多!
Common sparse basis and matlab code for compressed sensing
MySQL的存储过程
"Food alliance ordering system"
Shell programming specifications and variables
Camera Hal OEM模块 ---- cmr_preview.c
15. Model evaluation and selection
PTA (daily question) 7-75 how many people in a school
ORACLE not available如何解决
MQ 消息丢失、重复、积压问题,如何解决?
数仓搭建——DWT层
会议OA项目之会议通知&会议反馈&反馈详情功能
Depth first search (DFS) and its matlab code
MySQL的隔离级别、可能出现的问题(脏读、不可重复读、幻读)及其解决方法
Upload Excel files with El upload and download the returned files
“吃货联盟定餐系统”
16. Influence of deviation, variance, regularization and learning curve on the model