提高Matlab代码效率(improveMatlabPerformance)_第1页
提高Matlab代码效率(improveMatlabPerformance)_第2页
提高Matlab代码效率(improveMatlabPerformance)_第3页
提高Matlab代码效率(improveMatlabPerformance)_第4页
提高Matlab代码效率(improveMatlabPerformance)_第5页
已阅读5页,还剩17页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Matlab code performanceMatlab code performance肖昌炎肖昌炎湖南大学湖南大学 自动化系自动化系Part I: Techniques for Improving PerformancePart I: Techniques for Improving Performance Preallocating Arraysticx = 0;for k = 2:1000000 x(k) = x(k-1) + 5;endtocElapsed time is 0.301528 seconds.ticx = zeros(1, 1000000);for k = 2:100

2、0000 x(k) = x(k-1) + 5;endtocElapsed time is 0.011938 seconds.Use the appropriate preallocation function for the kind of array you want to initialize: zeros for numeric arrays cell for character arraysPreallocating a Nondouble Matrix A = int8(zeros(100); A = zeros(100, int8); Assigning VariablesIf y

3、ou need to store data of a different type, it is advisable to create a new variable. Changing the class or array shape of an existing variable slows MATLAB down because it takes extra time to process.You should not assign a real value to a variable that already holds a complex value, and vice versa.

4、 Assigning a complex number to a variable that already holds a real number impacts the performance of your program.X = 23; .- other code - .X = A; % X changed from type double to char .- other code - Using Appropriate Logical OperatorsOperator Description&, | Perform logical AND and OR on arrays

5、 element by element&, | Perform logical AND and OR on scalar values with short-circuitingIn if and while statements, it is more efficient to use the short-circuit operators, & and |:if (isnumeric(varargin1) & (ischar(varargin2)Additional Tips on Improving PerformanceAdditional Tips on Im

6、proving Performance Split large script files into smaller ones, having the first file call the second if necessary. Construct separate functions (or local functions and nested functions) from the larger chunks of code. If you have overly complicated functions or expressions, use simpler ones to redu

7、ce size. Simpler functions often make good utility functions that you can share with others. Use functions instead of scripts because they are generally faster. Vectorize your code to take advantage of the full functionality of MATLAB. Use a sparse matrix structure to vectorize code without requirin

8、g large amounts of memory. Avoid running large processes in the background while executing your program in MATLAB. Avoid overloading MATLAB built-in functions on any standard MATLAB data classes because this can negatively affect performance.Part II: VectorizationPart II: Vectorization Using Vectori

9、zation Indexing Methods for Vectorization Array Operations Logical Array Operations Matrix Operations Ordering, Setting, and Counting Operations Functions Commonly Used in VectorizingUsing VectorizationUsing Vectorizationi = 0;for t = 0:.01:10 i = i + 1; y(i) = sin(t);End=t = 0:.01:10;y = sin(t);%co

10、mputes the cumulative sum of a vector at every fifth element:x = 1:10000;ylength = (length(x) - mod(length(x),5)/5;y(1:ylength) = 0;for n= 5:5:length(x) y(n/5) = sum(x(1:n);End=x = 1:10000;xsums = cumsum(x);y = xsums(5:5:length(x);Indexing Methods for VectorizationIndexing Methods for Vectorization

11、Subscripted Indexing%1D arrayA = 6:10;A(3 5)%2D arrayA = 11 12 13; 14 15 16; 17 18 19A(2:3,2:3) Linear IndexingA = 11 12 13; 14 15 16; 17 18 19;A(6)A(3,1,8)A(3;1;8)Note: Use the functions sub2ind and ind2sub to convert between subscripted and linear indices. Logical IndexingMATLAB selects elements o

12、f A that contain a 1 in the corresponding position of the logical matrix:A = 11 12 13; 14 15 16; 17 18 19;A(logical(0 0 1; 0 1 0; 1 1 1)Array OperationsArray Operationsfor n = 1:10000 V(n) = 1/12*pi*(D(n)2)*H(n);End% Vectorized CalculationV = 1/12*pi*(D.2).*H;Logical Array OperationsLogical Array Op

13、erationsD = -0.2 1.0 1.5 3.0 -1.0 4.2 3.14;%You can directly exploit the logical indexing power of MATLAB to select the valid cone volumesVgood = V(D = 0);%MATLAB can compare two vectors of the same size, allowing you to impose further restrictions.V(V = 0) & (D H)Matrix OperationsMatrix Operati

14、onsx = -2:0.2:2;y = -1.5:0.2:1.5;X,Y = meshgrid(x,y);F = X.*exp(-X.2-Y.2);=%Constructing MatricesA = ones(5,5)*10;v = 1:5;A = repmat(v,3,1)A = repmat(1:3,5,2)B = repmat(1 2; 3 4,2,2)A = 97 89 84; 95 82 92; 64 80 99;76 77 67;. 88 59 74; 78 66 87; 55 93 85;dev = bsxfun(minus,A,mean(A)Ordering, Setting

15、, and Counting OperationsOrdering, Setting, and Counting Operations Eliminating Redundant Elementsx = 2 1 2 2 3 1 3 2 1 3;x = sort(x);difference = diff(x,NaN);y = x(difference=0)=y=unique(x); Counting Elements in a Vectorx = 2 1 2 2 3 1 3 2 1 3;x = sort(x);difference = diff(x,max(x)+1);count = diff(

16、find(1,difference)y = x(find(difference)count_nans = sum(isnan(x(:);count_infs = sum(isinf(x(:);Functions Commonly Used in VectorizingFunctions Commonly Used in VectorizingallTest to determine if all elements are nonzeroanyTest for any nonzeroscumsumFind cumulative sumdiffFind differences and approx

17、imate derivativesfindfind indices and values of nonzero elementsind2sub Convert from linear index to subscriptsipermuteInverse permute dimensions of a multidimensional arraylogical Convert numeric values to logicalmeshgridGenerate X and Y arrays for 3-D plotsndgrid Generate arrays for multidimension

18、al functions and interpolationspermuteRearrange dimensions of a multidimensional arrayprodFind product of array elementsrepmat Replicate and tile an arrayReshape Change the shape of an arrayshiftdimShift array dimensionssortSort array elements in ascending or descending ordersqueezeRemove singleton

19、dimensions from an arraysub2ind Convert from subscripts to linear indexsumfind the sum of array elementsPart III Matrix Indexing in MATLABPart III Matrix Indexing in MATLAB Indexing Vectorsv = 16 5 9 4 2 11 7 14;v(3) % Extract the third elementv(1 5 6) % Extract the first, fifth, and sixth elementsv

20、(3:7) % Extract the third through the seventh elementsv2 = v(5:8 1:4) % Extract and swap the halves of vV(end) % Extract the last elementv(2:end-1) % Extract the second through the next-to-last elements Indexing Matrices with Two SubscriptsA = magic(4) A(2,4) % Extract the element in row 2, column 4

21、A(2:4,1:2) A(3,:) % Extract third row A(:,end) % Extract last column Linear Indexing A(6 12 15) idx = sub2ind(size(A), 2 3 4, 1 2 4) If I want to shift the rows of an m-by-n matrix A by k places, I use A(:,n-k+1:n 1:n-k). But what if k is a function of the row number? That is, what if k is a vector of length m? Is there a quick and easy way to do this?% index vectors for rows and columns p = 1:m; q = 1:n; % index matrices

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论