Summary of MATLAB Notes (1) Donghua University MOOC

insert image description here
insert image description here
insert image description here
insert image description here

loop statement

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

MATLAB function handle

https://zhuanlan.zhihu.com/p/266263265

https://blog.csdn.net/shaozheng0503/article/details/130305984?spm=1001.2014.3001.5501

insert image description here

data and variables

expression

semicolon;) comma (, ), ellipsis (3 English periods...).

Calling historical instructions: use the arrow keys (↑↓)

data display format

format short

format long

format rational

The difference between display format and counting precision

plural i, j

predefined variable

pi 3.1415…

eps floating point recognition precision 2.22×10-16

realmin The smallest positive real number 2.2251×10 -308

realmax Maximum positive real number 1.7977×10308

infinity

NaN indefinite value

user variables

Naming rules: beginning with a letter, composed of letters, numbers or underscores, case-sensitive (can there be punctuation marks?) to prevent the system's predefined variable names (such as i, j, pi, eps, etc.), function names (such as who , length, etc.), reserved words (for, if , while, end, etc.) conflict.

special variable ans

It is a special variable name of the system itself. If the operation result is not assigned to
any variable, the system will assign it
to clear with ans clear (note
the difference between Clear Workspace and Clear Command Window.)

data file

Realize exchange with external data files: mat, txt, etc.
Menu methods: Save Workspace and Import Data

Example: save-clear-import
command mode: save and load

C language method:

fprintf, fsacnf,fopen, fread

例 : file = fopen(‘ceg.txt’,‘w’);

fprintf(file,‘%12.8f %6.2f\n’,[pi, 2*pi]);

fclose(file);

Called with load or import data

Arrays and their operations

a=[1 2 3;4 5 6;7 8 9]

Brackets [ ] represent a matrix, elements in the same line are separated by spaces or commas
, and different lines are separated by semicolons or carriage returns.

colon operation

The function linspace(x1,x2,n) generates an n-dimensional equidistant
row vector between x1 and x2, that is, [x1,x2] n-1 equal division

length, size

Addressing: cannot be 0, addressing by column, such as a(6)

query, change(a(m,n)), extract(a([1,3,2])), splice([A, B], [A; B] ), delete(A(i1:i2, : )=[ ])

sum, prod, min, max

special matrix

Zero matrix (zeros(m,n)), one matrix (ones(m,n)), identity matrix
(eye(m,n))

Import external Excel data files

Clipboard+Array Editor

menu import data

Array operation
A+B and AB add and subtract

k A or A k multiplication matrix

k+A and kA k plus (minus) each element of A

A.^k , k.^A array power

A.*B array multiplied by array

k./A number divided by an array

Left division A.\B=Right division B/.A Array division

The point operation is the operation corresponding to the element

Example (note the difference between point operation and matrix operation)

math function

Mathematical functions for matrices also operate element-wise, using the usual function numbers,

如sin(A), cos(A), asin(A), acos(A)tan(A), cot(A), exp(A), sqrt(A) ratio.

fix rounds floor to 0

Round towards -∞

ceil Round towards +∞

mod modular division remainder

rem division remainder

abs Absolute value (modulo)

real complex real part

imag complex imaginary part

angle complex argument angle

conj complex conjugate

log natural logarithm

ln log10 base 10 logarithm

Relational and Logical Operations

< , <= less than, less than or equal to

, >= greater than, greater than or equal to

= = , ~ = equal to, not equal to

& (and), | (or), ~ (not)

any、all 、find

In MATLAB, "true" is represented by 1, "false" is represented by 0, and in logical operations, all non-zero elements are treated as 1

type of data:

Value (Double)

Logical

Character (Char)

Cell

Structure

string

Single quotation marks (English half-width input status!)

Chinese characters: a='Qingxin Mingmu', b=a([4: -1:1])

Do not copy after typing in word (single quotes change!)

Characters within quotation marks should be displayed in lavender

String concatenation: t=' ok? ', c=[a([3,4,1,2]), t]

String conversion double, char, num2str, str2num

Comparison: a='12',b=double(a),c=str2num(a)

eval executes instructions written in strings (example)

cells and structures

Numeric and character mixed

cell { }

Structure: the concept of domains

struct2cell和cell2struc

2.1 Program design

M script file

function file

other

branch statement

if (conditional), statement; end

if (condition 1), statement 1; elseif (condition 2),

statement 2; ...;else, statement;end
switch(branch variable)case(value 1), statement 1;case(value 2), statement
2;...;otherwise statement;end

loop statement

for loop variable = initial value: increment: final value, statement; end

while (conditional), statement; end

Others: pause, break, return, error

M script file

M脚本文件通常是一种Matlab脚本文件,它包含一组MATLAB命令和函数,可用于执行特定的操作。由于MATLAB是一种计算机语言和开发环境,其主要用于工程学、科学研究和数据分析等领域,因此M脚本文件通常用于执行这些领域的任务。

M脚本文件可以使用任何文本编辑器创建,例如Windows记事本或Notepad++。它们以“.m”作为文件扩展名,并使用MATLAB软件来编译和运行。

创建一个M脚本文件非常简单,只需在文本编辑器中打开新文件并按照所需的命令格式输入MATLAB代码即可。例如,以下是一个简单的M脚本示例,可用于计算圆的面积:

```
% This is a comment in the M script file
r = 5; % radius of the circle
area = pi*r^2; % calculate the area
disp(['The area of the circle is ', num2str(area)]) % display the result
```

在此示例中,该脚本文件定义了圆的半径,并使用MATLAB内置的pi函数和幂运算符计算圆的面积。最后,使用disp函数在命令窗口中显示结果。

M脚本文件是MATLAB编程语言中的基本元素之一,是许多MATLAB程序的基础。

调用M脚本文件通常需要使用MATLAB软件。你可以通过以下步骤来调用一个M脚本文件:

1. 在MATLAB软件中打开“当前文件夹”窗口,这可以通过在命令窗口中输入“cd”命令或使用菜单选项“Current Folder”来实现。

2. 将M脚本文件移动到打开的“当前文件夹”窗口中。

3. 在命令窗口中输入M脚本文件的名称,然后按下回车键即可执行该脚本。例如,如果文件名为“myscript.m”,则可以在命令窗口中输入“myscript”并按下回车键。

4. MATLAB将加载并运行M脚本文件中的所有命令和函数。你可以在命令窗口中查看输出结果,并在必要时更改M脚本文件中的代码。

此外,还可以通过在MATLAB中创建一个函数句柄来调用M脚本文件,或者通过使用适当的命令将M脚本文件作为其他MATLAB程序的一部分进行调用。

调用M脚本文件通常需要使用MATLAB软件。你可以通过以下步骤来调用一个M脚本文件:

1. 在MATLAB软件中打开“当前文件夹”窗口,这可以通过在命令窗口中输入“cd”命令或使用菜单选项“Current Folder”来实现。

2. 将M脚本文件移动到打开的“当前文件夹”窗口中。

3. 在命令窗口中输入M脚本文件的名称,然后按下回车键即可执行该脚本。例如,如果文件名为“myscript.m”,则可以在命令窗口中输入“myscript”并按下回车键。

4. MATLAB将加载并运行M脚本文件中的所有命令和函数。你可以在命令窗口中查看输出结果,并在必要时更改M脚本文件中的代码。

此外,还可以通过在MATLAB中创建一个函数句柄来调用M脚本文件,或者通过使用适当的命令将M脚本文件作为其他MATLAB程序的一部分进行调用。

function file in matlab

MATLAB中的函数文件是一种用于封装代码或算法的文件类型。MATLAB函数包含一组指令和变量,它们可以被主程序或其他代码所调用以执行特定的任务。

MATLAB函数与脚本文件不同,因为函数具有输入和输出参数,并且通常用于重复使用和模块化编程。MATLAB函数文件由以下三部分组成:

- 函数声明行
- 函数体
- 输出语句

下面是一个简单的例子,说明如何创建一个MATLAB函数文件来计算两个数的乘积:

```
function mult_result = multiply(num1, num2)
% FUNCTION to calculate the product of two numbers
% INPUTS : num1 and num2 are input parameters of the function
% OUTPUT : mult_result is the result of multiplying num1 to num2
mult_result = num1 * num2; % perform multiplication
end
```

以上函数声明行中“function”关键字定义了一个名为“multiply”的函数,其可接收两个输入参数“num1”和“num2”。该函数的输出结果存储在变量“mult_result”中,并最后返回该结果。

将上述代码保存为以“.m”结尾的文本文件,以便作为MATLAB函数文件使用。然后,你可以通过键入函数名称和输入参数来调用该函数。例如,下面的命令可以调用该函数并将输出打印到命令行窗口:

```
>> a = 3;
>> b = 4;
>> c = multiply(a, b);
>> disp(c);
12
```

MATLAB中的函数文件可以直接通过函数名称调用,也可以作为另一个程序或脚本文件的一部分调用。

Analysis of different sentences and explanation of basic concepts

insert image description here
insert image description here
insert image description here

function handle

Write M function eg2_1f.m
function handle fname=@eg2_1f;
feval (fname,1000) or fname(1000)
Note the difference between feval and eval

>>m=1000;
>>str= 'sum(1./(1:m).^2';
>>eval(str)

inline function and anonymous function

inline函数
fun=inline(‘函数表达式’, ‘自变量’)
>> fname=inline('sum(1./(1:m).^2)','m') 
>> fname(1000) 
匿名函数
fun=@(自变量)函数表达式
匿名函数的参数传递更灵活
>> k=2; fname=@(m)sum(1./(1:m).^k)
>> fname(1000)

explain

MATLAB中的inline函数和匿名函数都可以用于创建轻量级的小型函数,但它们之间仍然有一些不同之处。

1. inline函数

inline函数是一个用于逐元素数学运算的函数,其中输入输出变量必须使用列向量。它们通常用于快速编写简单数学表达式的程序。需注意的是,从MATLAB 2016a开始,已不再推荐使用inline函数,现在建议使用匿名函数或函数句柄来代替。

以下是inline函数的一个例子:

```
f = inline('sin(x)^2 + cos(x)^2')
x = -pi:0.01:pi;
y = f(x);
plot(x,y)
title('Output of Inline Function')
```

在上面的程序中,我们使用inline函数定义一个用于计算“sin(x)^2 + cos(x)^2”的函数,并将其存储在变量“f”中。然后我们定义一系列变量并将其传递给函数,最终通过“plot”函数绘制输出结果。

2. 匿名函数

匿名函数是一种便于创建短小精悍的函数的方式,它们可以被重复使用和模块化编程。与inline函数使用字符串输入不同,匿名函数使用符号输入。下面是一个使用匿名函数的例子:

```
g = @(x,y) sin(x)*cos(y)
z = g(pi/4, pi/6)
```

在上面的例子中,我们使用@符号定义了一个匿名函数“g”,该函数计算指定范围内sin(x)和cos(y)之间的乘积。我们用pi/4pi/6调用该函数,并将结果存储在变量“z”中。

与inline函数相比,匿名函数是更加最新和建议的选项。“@”符号可以让用户轻松地以代码块形式定义任意复杂度的函数,并自由传递它们。

Other - data input and output

input function: Prompt the user to enter data A=input (prompt information, options):

disp function: screen output disp (output item)

Because the output of the disp function is a string. If you want to output numbers, you must first convert the numbers into strings.

Find the root of ax2+bx+c=0.
The procedure is as follows:

a=input('a=?")
b=input('b=?');
c=input('c=);
d=b*b-4*a*c;
X=[(-b+sqt(d)/(2*a),(b-sqrt(d))/(2*a)];
disp(['x1=',num2str(x(1)),',x
2=',num2str(x(2));

Other - function overloading nargin and nargout

nargin: record the number of input variables when calling the function;

nargout: Record the number of output variables when calling the function.

Example: function file exam_arg.m:

function [f1,f2]=exam_arg(a,b,c)
if nargin==1
f1=a;
elseif nargin==2 f1=(a+b)/2;
elseif nargin==3
f1=(a+b+c)/3;
end
if nargout==0
error(('没有输出参数。)elseif nargout==2
f2=计算平均值'end

increase speed

insert image description here

2.2 Drawing

Graph
The most basic function for drawing a curve:
plot(x,y) : x and y are vectors with the same length, which are used to store x-
coordinate and y-coordinate data respectively.

plot(x1, y1, option 1, x2, y2, option 2, ..., xn, yn, option n) : multiple
groups of polylines

plot3(x1, y1, z1, option 1,..., xn, yn, zn, option n): space curve fplot('fun', [a, b]): draw the graph of fun on the interval [a, b] fun can be a function or an expression The procedure for using the plot function is as follows:

x=0:pi/100:2*pi;
y=2*exp(-0.5*x).*sin(2*pi*x);
plot(x,y,'r*') %分别以x,y对应的元素为横、纵坐标绘制曲线。

Graphic export method:

1. File->Save->graphics file

2. Edit->Copy figure->Paste to the specified file
In the interval of 0≤X≤2, draw the curve y=2e-0.5xsin(2πx) or use the fplot function: fplot(@(x)2 exp(-0.5 x ) sin(2 pi x),[0,2 pi],'gd')

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-lugzsagD-1685846200209)(2023-06-04-10-26-47.png)]

Draw a 3D parametric curve

t=0:pi/50:2*pi;
x=8*cos(t);y=4*sqrt(2)*sin(t);
z=-4*sqrt(2)*sin(t);
plot3(x,y,z,'p')

Example: draw sine, cosine and other curves in one window at the same time.

x=linspace(0,2*pi,60);
y=sin(x);z=cos(x);
subplot(2,2,1); %选择2×2区中的1号区
plot(x,y); title('sin(x)'); axis ([0,2*pi,-1,1]); 
subplot(2,1,2); %选择2×1区中的2号区
plot(x,z, '*'); title('cos(x)'); axis ([0,2*pi,-1,1]); 
x=linspace(-2,2,60);
y=x.^3; 
subplot(2,2,2); %选择2×2区中的2号区
plot(x,y); title('x^3'); axis ([-2,2,-4,4]);

!](https://img-blog.csdnimg.cn/c154d7b4a30b422499ffd0d7f4923034.png#pic_center)
insert image description here

Guess you like

Origin blog.csdn.net/shaozheng0503/article/details/131029647