[Matlab] How to improve the efficiency of program operation [GO]

Source: Internet
Author: User
Tags cos

1. Cyclic vectorization
MATLAB is designed for vector and matrix operations, so you can accelerate the operation of M files by Vectorization. Vectorization refers to converting a For loop and a while loop to an equivalent vector or matrix operation. An example of a loop is given below:
i=0;
For n = 0:0.1:1000
i=i+1;
Y (i) =cos (n);
End
Then we can vectorize to:
N= 0:0.1:1000;
Y=cos (n);
We can use TIC and TOC functions to see how long each of these code runs, with a for-loop program of 0.39 seconds (specific time and computer Configuration), and Vectorization takes almost 0.

2. Pre-allocating memory to arrays or matrices
Especially when using large arrays or matrices, when MATLAB makes dynamic memory allocations and cancellations, memory fragmentation can occur, which results in a lot of idle memory generation, and pre-allocation can avoid this problem by reserving enough space in advance for large data structures.

3. Replace the script file with a function
Because each script file that calls MATLAB needs to load unnecessary intermediate variables into memory, each time it is executed, it is loaded once. The function is compiled into pseudo-code at the time of invocation and only needs to be loaded into memory once. It runs faster when the same function is called more than once. Therefore, it is also a way to improve execution efficiency by using the function files as much as possible and using less script files.

4. Write the Loop code in a MEX file
MATLAB provides interfaces with C and C + +, then we can write in C or C + + language time-consuming loop code, and then through the interface program in MATLAB to switch to DLL files, this is what we want the Mex file, this method can greatly improve the calculation rate.

[Matlab] How to improve the efficiency of program operation [GO]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.