当前位置:网站首页>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
边栏推荐
- “吃货联盟定餐系统”
- PTA (daily question) 7-74 yesterday
- MQ 消息丢失、重复、积压问题,如何解决?
- PTA (daily question) 7-70 diamond
- "Food alliance ordering system"
- Outlier detection and open set identification (2)
- 【开发教程11】疯壳·开源蓝牙心率防水运动手环-整机功能代码讲解
- I don't know how lucky the boy who randomly typed the log is. There must be a lot of overtime!
- MySQL stored procedure
- 乱打日志的男孩运气怎么样我不知道,加班肯定很多!
猜你喜欢

PTA (one question per day) 7-76 ratio

MySQL stored procedure

Application and principle of distributed current limiting redistribution rratelimiter

Teach you how to install latex (nanny level tutorial)

Data warehouse construction - ads floor

PTA (daily question) 7-69 narcissus number

Outlier detection and Gan network (1)
![[development tutorial 11] crazy shell · open source Bluetooth heart rate waterproof sports Bracelet - explanation of the function code of the whole machine](/img/a1/9a69e5d123a8a11504da251bd1bcfc.png)
[development tutorial 11] crazy shell · open source Bluetooth heart rate waterproof sports Bracelet - explanation of the function code of the whole machine

我不建议你使用SELECT *

Recursion / backtracking (Part 2)
随机推荐
【网络安全】通过iptables和ipset完成服务器防火墙黑名单和白名单功能
flyway的快速入门教程
Execute immediate simple sample set (DML)
Dynamic programming problem (6)
Outlier detection and open set identification (1)
NPM run serve stuck at 40%
Dynamic programming problem (VIII)
Dynamic programming problem (VII)
Software designer afternoon question
MySQL sub database and sub table and its smooth expansion scheme
SAP VL02N 交货单过账函数 WS_DELIVERY_UPDATE
Alibaba Code代码索引技术实践:为Code Review提供本地IDE的阅读体验
芯驰科技发布G9系列最新旗舰产品,配备6个1.8Ghz主频的A55核心
Data warehouse construction - ads floor
MySQL stored procedure
mysql时间按小时格式化_mysql时间格式化,按时间段查询的MySQL语句[通俗易懂]
R语言怎么学
[basic course of flight control development 8] crazy shell · open source formation uav-i2c (laser ranging)
Shell programming specifications and variables
Cause analysis of 12 MySQL slow queries