【转载】让你的MATLAB运行效率更快一些吧!

【转载】让你的MATLAB运行效率更快一些吧!,第1张

转自 https://wwwdigquantcomcn/forumphpmod=viewthread&tid=258

1、改变算法,多用矩阵运算(尤其是矩阵乘法),尽量减少for循环;

2、减少for循环中的函数调用;

传统观点认为for-loop是影响性能的致命环节,让我们来对此验证:

Elapsed time is 0000239 seconds

Elapsed time is 0000050 seconds

从上面的实验结果可以得出以下结论:

1、tic/toc语句的时间开销可以忽略不计

2、for-loop语句本身的时间开销也非常小,关键的影响效率的地方不在于循环本身,而是在于循环的内部。

3、tic/toc不一定要成对出现,一个tic后面可以有多个toc,但需要需要重新计时的时候,要再次执行tic。

4、toc的结果可以用变量接收下来,如:

接下来我们就借助for循环,分析一下其他的各个影响效率的因素。

内建函数

Mean elapsed time is 0032866 seconds

m-函数

Mean elapsed time is 0185556 seconds

匿名函数

Mean elapsed time is 0561228 seconds

内联函数

Mean elapsed time is 195606 seconds

从上面的实验结果可以得出以下结论:

1、内联函数的调用时间开销最小,约为for-loop本身的10倍

2、m-函数的调用时间开销约为内联函数的6倍,约为for-loop本身的60倍

3、匿名函数的调用时间开销约为m-函数的3倍,约为for-loop本身的187倍

4、内联函数的调用时间开销过大,尽量不要在循环中使用

5、另外MEX-函数的调用时间开销,理应介于内联函数和m-函数之间

矩阵索引

Mean elapsed time is 0007592 seconds

Mean elapsed time is 0007954 seconds

Mean elapsed time is 0663598 seconds

Mean elapsed time is 0273345 seconds

Mean elapsed time is 0730042 seconds

Mean elapsed time is 100852 seconds

Mean elapsed time is 0009025 seconds

Mean elapsed time > 20 minutes

因此,如果不预先分配好内存,将会大大增加仿真时间,拖慢执行效率。

所幸的是,由于这个现象的重要性,Matlab的编辑器能够发现并提示这个问题,会用红的波浪线 ~ 标记出来。

向量化:

MATLAB向量化函数

accumarray函数

arrayfun函数

bsxfun函数

cellfun函数

spfun函数

A =

101

206

0

208

subs =

1 1 1

2 1 2

2 3 2

2 1 2

2 3 2

val =

101

102

103

104

105

1、val的元素个数与subs的行数是一致的。

2、 A = accumarray(subs, val) 的实现过程分成2步。

第一步

是把val中的元素,按照subs对应行所给出的下标放到一个新的cell矩阵B中(cell是为了方便解释,也就是说B矩阵中的每个位置可以放入多个数值),注意,subs的值是B的下标,不是val的。举例来说,subs第一行[ 1 1 1],意思就是把val中第一个元素(val(1))放入到B(1,1,1)的位置,依次类推,val(2)放入到B(2 1 2),val(3)放入到B(2 3 2),val(4)放入到B(2 1 2),val(5)放入到B(2 3 2)。此时,可以看到B(1,1,1)中有1个数(val(1));B(2 1 2)有2个数(val(2),val(4));B(2 3 2)也有2个数(val(3),val(5))。

第二步

把B中每个单元中的数分别累加,并放入到A的对应位置。

注: accumarray 默认的是把每个单元中的数累加,因为对每个单元中的数的默认处理函数是sum。可以通过 A = accumarray(subs,val,[],[@fun](https://githubcom/fun "@fun")) 的调用格式来指定其他的处理函数,比如说mean。对指定的fun函数的要求是,接受列向量输入,输出单个的数值型,字符型或逻辑型变量。A的维数与B相同,A中的元素默认为零。A的大小为max(subs(1))×max(subs(2))×max(subs(3))…

很显然,A的维数与subs的列数相等。

例子:

1000人,身高分布在170 180cm,体重在110 100斤,年龄分布在20~50岁,计算身高体重都相等的人的年龄平均值。结果用矩阵来表示:行数表示身高,列数表示体重,矩阵元素表示年龄的平均值。

arrayfun函数实现的是将指定的函数应用到给定数组在内的所有元素。这样以前不可避免的循环现在可以向量化了。

生成一个这样的n×n矩阵

以前,当我们想对一个矩阵A的每一列或每一行与同一个向量a进行某些操作(比较大小、乘除等)时,只能用循环方法或者利用repmat函数将要操作的向量a复制成和A一样尺寸的矩阵,进而进行操作。从Matlab R2007a开始,有了更有效的方法,那就是bsxfun函数。

有如下矩阵:

向量为b=[1 2 3]T,请找出b在A矩阵列中的位置loc=[1,4]。

方法1:

方法2:

方法3:

方法4:

方法5:

A={‘Hello’, ‘MATLAB’, ‘I love MATLAB’, ‘MATLAB is powerful’, ‘MATLAB is the language of technical computer’};

cellfun( @length ,A)

ans =

5 6 13 18 44

</pre>

a =

(1,2) 1

(3,20) 2

(20,30) 3

(60,60) 4

(100,80) 5

</pre>

sa =

(1,2) 2

(3,20) 5

(20,30) 10

(60,60) 17

(100,80) 26

常用的预分配内存函数:

punct - Function handle creation @

@ 在匿名函数中表示函数句柄

例如ln(x),在matlab中是没有定义的,正确表示是log(x);

但如果要直观表示自然对数,意义用以下语句表示:

ln=@(x) log(x);

执行后,ln(4)=log(4) , 即用ln 替换 log。

以上表示可能无法看出‘@’的好处,再看下例:

poly6 = @(x) 8x^6+6x^5+3x^3+x^2+x+520;

fplot(ploy6,[0,100]);

fzero(ploy6,13);

在这种长且多次调用的情况下,用函数句柄就可以方便很多。

MATLAB

From Wikipedia, the free encyclopedia

Jump to: navigation, search

MATLAB

MATLAB 65 being used to manipulate a bitmap image

Developer: The MathWorks

Latest release: R2006b / September 1, 2006

OS: Cross-platform (list)

Use: Technical computing

License: Proprietary

Website: MATLAB product page

MATLAB is a numerical computing environment and programming language Created by The MathWorks, MATLAB allows easy matrix manipulation, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages Although it specializes in numerical computing, an optional toolbox interfaces with the Maple symbolic engine, allowing it to be part of a full computer algebra system

It is used by more than one million people in industry and academia[1] A North American individual commercial license costs US$1900 (MATLAB only), while a license for student use costs US$99 (MATLAB, Simulink and Symbolic Math) [2]

Contents

[hide]

1 History

2 Syntax

o 21 Variables

o 22 Vectors/Matrices

o 23 Semicolon

o 24 Graphics

3 Code Snippets

4 Limitations

5 See also

6 Notes

7 References

8 External links

[edit] History

Short for "MATrix LABoratory", MATLAB was invented in the late 1970s by Cleve Moler, then chairman of the computer science department at the University of New Mexico He designed it to give his students access to LINPACK and EISPACK without having to learn Fortran It soon spread to other universities and found a strong audience within the applied mathematics community Jack Little, an engineer, was exposed to it during a visit Moler made to Stanford University in 1983 Recognizing its commercial potential, he joined with Moler and Steve Bangert They rewrote MATLAB in C and founded The MathWorks in 1984 to continue its development These rewritten libraries were known as JACKPAC

MATLAB was first adopted by control design engineers, Little's specialty, but quickly spread to many other domains It is now also used in education, in particular the teaching of linear algebra and numerical analysis, and is the de facto choice for scientists involved with image processing

[edit] Syntax

MATLAB is built around the MATLAB language, sometimes called M-code or simply M The simplest way to execute M-code is to type it in at the prompt, >> , in the Command Window, one of the elements of the MATLAB Desktop In this way, MATLAB can be used as an interactive mathematical shell Sequences of commands can be saved in a text file, typically using the MATLAB Editor, as a script or encapsulated into a function, extending the commands available

[edit] Variables

Variables are defined with the assignment operator, = MATLAB is dynamically typed, meaning that variables can be assigned without declaring their type, and that their type can change Values can come from constants, from computation involving values of other variables, or from the output of a function For example:

>> x = 17

x =

17

>> x = 'hat'

x =

hat

>> x = 34

x =

12

>> y = 3sin(x)

y =

-16097

[edit] Vectors/Matrices

MATLAB is the "Matrix Laboratory", and so provides many convenient ways for creating matrices of various dimensions In the MATLAB vernacular, a vector refers to a one dimensional (1×N or N×1) matrix, commonly referred to as an array in other programming languages A matrix generally refers to a multi-dimensional matrix, that is, a matrix with more than one dimension, for instance, an N×M, an N×M×L, etc, where N, M, and L are greater than 1 In other languages, such a matrix might be referred to as an array of arrays, or array of arrays of arrays, etc

MATLAB provides a simple way to define simple arrays using the syntax: init:increment:terminator For instance:

>> array = 1:2:9

array =

1 3 5 7 9

defines a variable named array (or assigns a new value to an existing variable with the name array) which is an array consisting of the values 1, 3, 5, 7, and 9 That is, the array starts at 1, the init value, and each value increments from the previous value by 2 (the increment value), and stops once it reaches but not exceeding 9 (9 being the value of the terminator)

>> array = 1:3:9

array =

1 4 7

the increment value can actually be left out of this syntax (along with one of the colons), to use a default value of 1

>> ari = 1:5

ari =

1 2 3 4 5

assigns to the variable named ari an array with the values 1, 2, 3, 4, and 5, since the default value of 1 is used as the incrementer

Matrices can be defined by separating the elements of a row with blank space or comma and using a semicolon to terminate each row The list of elements should be surrounded by square brackets []

>> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]

A =

16 3 2 13

5 10 11 8

9 6 7 12

4 15 14 1

A square identity matrix of size n can be generated using the function eye, and matrices of any size with zeros or ones can be generated with the functions zeros and ones, respectively

>> eye(3)

ans =

1 0 0

0 1 0

0 0 1

>> zeros(2,3)

ans =

0 0 0

0 0 0

>> ones(2,3)

ans =

1 1 1

1 1 1

[edit] Semicolon

In many other languages, the semicolon is required to terminate commands In MATLAB the semicolon is optional If a statement is not terminated with a semicolon, then the result of the statement is displayed [3]

[edit] Graphics

Function plot can be used to produce a graph from two vectors x and y The code:

x = 0:pi/100:2pi;

y = sin(x);

plot(x,y)

produces the figure of a sinusoid with frequency 1rad·s−1:

Three dimensional graphics can be produced using the functions surf, plot3 or mesh

[X,Y] = meshgrid(-8:5:8);

R = sqrt(X^2 + Y^2)+eps;

Z = sin(R)/R;

surf(X,Y,Z)

This code produces the figure of a two-dimensional sinc function

[edit] Code Snippets

This code, excerpted from the function magicm, creates a magic square M for odd values of n

[J,I] = meshgrid(1:n);

A = mod(I+J-(n+3)/2,n);

B = mod(I+2J-2,n);

M = nA + B + 1;

Note that this code performs operations on vectors and matrices without the use of "for" loops Idiomatic MATLAB programs usually operate on whole arrays at a time The MESHGRID utility function above creates arrays like these:

J =

1 2 3

1 2 3

1 2 3

I =

1 1 1

2 2 2

3 3 3

Most scalar functions can also be used on arrays, and will apply themselves in parallel to each element Thus mod(2J,n) will (scalar) multiply the entire J array with 2, before reducing each element modulo n

MATLAB does include standard "for" and "while" loops, but using MATLAB's vectorized notation often produces code that is easier to read and faster to execute

Most commonly used functions are already included in MATLAB, and the same magic square could be obtained by using the magic function

magic(n)

[edit] Limitations

MATLAB is a proprietary product of The MathWorks, so users are subject to vendor lock-in

The language shows a mixed heritage with a sometimes erratic syntax For example, MATLAB uses parentheses, eg y = f(x), for both indexing into an array and calling a function Although this ambiguous syntax can facilitate a switch between a procedure and a lookup table, both of which correspond to mathematical functions, a careful reading of the code may be required to establish the intent

Many functions have a different behavior with matrix and vector arguments Since vectors are matrices of one row or one column, this can give unexpected results For instance, function sum(A) where A is a matrix gives a row vector containing the sum of each column of A, and sum(v) where v is a column or row vector gives the sum of its elements; hence the programmer must be careful if the matrix argument of sum can degenerate into a single-row array While sum and many similar functions accept an optional argument to specify a direction, others, like plot, do not, and require additional checks There are other cases where MATLAB's interpretation of code may not be consistently what the user intended (eg how spaces are handled inside brackets as separators where it makes sense but not where it doesn't, or backslash escape sequences which are interpreted by some functions like fprintf but not directly by the language parser because it wouldn't be convenient for Windows directories) What might be considered as a convenience for commands typed interactively where the user can check that MATLAB does what the user wants may be less supportive of the need to construct reusable code

Though other datatypes are available, the default is a matrix of doubles This array type does not include a way to attach attributes such as engineering units or sampling rates Although time and date markers were added in R14SP3 with the time series object, sample rate is still lacking Such attributes can be managed by the user via structures or other methods

Array indexing is one-based which is the common convention for matrices in mathematics, but does not accommodate the indexing convention of sequences that have zero or negative indices For instance, the DFT (or FFT) is defined with the DC component at index 1 instead of index 0, which is not consistent with the standard definition of the DFT This one-based indexing convention is hard wired into MATLAB, making it impossible for a user to define their own zero-based or negative indexed arrays to concisely model an idea having non-positive indices

MATLAB doesn't support references, which makes it difficult to implement data structures that contain indirections, such as open hash tables, linked lists, trees, and various other common computer science data structures In addition, since the language is consistently call-by-value, it means that functions that modify array or object values must return and assign those modified values for the change to be persistent

Matlab-2018a软件+教程百度网盘免费资源在线学习  

   yc8c   

 Matlab-2018a软件+教程 内容截图展示 64位电脑建议下这个 32位电脑只能下这个 matlab 2014a(支持32位、64位)zip 

2014A安装教程mp4 Matlab-2018a破解版安装包zip 

3png 2png 1png    

diff(v):求一阶导数;sign:确定的符号,只有1或-1;Lmax可能为0,-2,2,f'左右必须是异号且f''小于0才是最大值,所以-2。

其余的不解释了,太多,首先你要了解极大值、极小值的概念和定理。

1、打开用matlab做好的一个图。

2、然后打开之后,就是需要点击菜单栏上面的插入选项。

3、然后在插入选项中,如图所示,点击选择文本箭头。

4、然后接下来在图中添加一个箭头为标注,如图所示,会出现文本输入框。

5、最后,如图所示,然后在文本输入框中输入文字及说明。

欢迎分享,转载请注明来源:表白网

原文地址:https://h5.hunlipic.com/biaobai/4169099.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2024-04-20
下一篇2024-04-20

发表评论

登录后才能评论

评论列表(0条)

    保存