Repost] (translation) Matlab code vectorization guide-1

zhaozj2021-02-12  142

Sender: MARS (Fangq), Word Area: Mathtools Title: (Translated) Matlab Code Vectorization Guide - COOLOR @ Smth [Reserved] Send Station: Amount Biggreen BBS (Mon Nov 11 13:54:55 2002), Station letter

Sender: COOLOR (2003 Spring Countdown), Letter: Mathtools Title: (Translated) MATLAB Code Vectorization Guide Send Station: BBS Shuimu Tsinghua Station (Tue Nov 12 00:43:16 2002),

This article is translated from http://www.mathworks.com/support/tech-notes/11109.shtmlrevison: 2.0 last Date Modified: 15-october-2002 Translation: COOLOR @ smth Thank: SMTH2008 @ smth provides his translation draft. This article refers to or references his translation ========================================= ================ 1, basic technology ------------------------------------------------------------------------------------------------------------------------------------ ----------------------- 1) Matlab Indexing or References There are three basic methods in MATLAB. You can choose a matrix of sub-array. They are subscript methods, linear methods and logical laws (Subscripted, Linear, and Logical). If you are familiar with this content, please skip this section 1.1) The subscript method is very simple, see a few examples. A = 6:12; A ([3, 5]) ANS = 8 10 A ([3: 2: End]) ANS = 8 10 12 A = [11 14 17; ... 12 15 18; ... 13 16 19] A (2: 3, 2) ANS = 15 16 1.2) Linear method The two-dimensional matrix can be linearly expanded in line priority, and the elements can be accessed by the currently expanded element sequence number. A = [11 14 17; ... 12 15 18; ... 13 16 19]; A (6) ANS = 16 A ([3, 1, 8]) ANS = 13 11 18 A ([3; 1 ; 8]) ANS = 13 11 18 1.3) Logic method with a 0-1 matrix of the same size in one and the original matrix, can index the element. In some position, 1 means the selection element, otherwise it will not be selected. The result is a vector. A = 6:10; A (Logical ([0 0 1 0 1])) ANS = 8 10 a = [1 2 3 4]; b = [1 0 0 1]; A (Logical (b)) ANS = 1 4 ----------------------------------------------------------------- ----- 2) Array Operations VS. Matrix Operations The action of an element of a matrix is ​​called an array operation; while the matrix is ​​considered to be a whole operation to become a matrix operation.

MATLAB operators *, /, /, ^ are all matrix operations, while the corresponding array operations are. *, ./, ./,. ^ A = [1 0; 0 1]; b = [0 1; 1 0]; a * b% matrix multiplication ANS = 0 1 1 0 A. * B% a and b correspondence item multiplied ANS = 0 0 0 0 ----------------- ------------------------------------ 3) Boolean Array Operations to matrices The comparative operation is an array operation, that is, it is performed for each element. Therefore, its result is not a "true" or "false", but a pile of "true and false". This result is a Brown array. D = [-0.2 1.0 1.5 3.0 -1.0 4.2 3.14]; D> = 0 ANS = 0 1 1 1 0 1 1 If you want to select the positive element in D: D = D (D> 0) D = 1.0000 1.5000 3.0000 4.2000 3.1400 In addition, NaN, INF, -INF will appear in the MATLAB operation. See the comparison of them, INF == INF Return true INF <1 Return to the fake nan == nan return hypothesis, you can use Isinf, ISNAN to judge, usage can be as namecing. When comparing two matrices, the matrix must have the same size, otherwise the error will be reported. This is the upper size and ISEqual, ISEqualwithequalnans (R13 and later). -------------------------------------------------- ---- 4) Creating a constant matrix from the vector build matrix (constructing matrix) is very simple in matlab, and everyone often uses: a = ones (5, 5) * 10, but you know, this multiplication is not necessary? A = 10; A = A (Ones (5, 5)) a = 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 Similar examples also: v = (1: 5) '; n = 3; m = v (:, ones (n, 1)) m =

1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 In fact, there is also a more easy understanding of understanding: a = repmat (10, [5 5]); m = repmat ([1: 5 ], [1,3]); wherein the meaning of RePmat is to repeat a matrix to create a larger matrix. For more details, see Functions RepMAT and Meshgrid. -------------------------------------------------- --- 5) Related Functions (Utility Functions "One of the 1 matrix ZEROS All 0 Matrix Reshape Modify Matrix Shape Repmat Matrix Table Meshgrid 3D PLOT You need to use the X-Y grid matrix NDGRID N-dimension PLOT needed X-Y-Z ... grid matrix FILTER One-dimensional digital filter, is particularly useful when the array elements are related. Step by step of Cumsum array element Step by step by step EYE unit matrix DIAG generates a diagonal matrix or a matrix diagonal SPDIAGS Sparse diagonal matrix Gallery Different Type Matrix Pascal Pascal Matrix Hankel Hankel Matrix TOEPLITZ TOEPLITZ Matrix

============================================================================================================================================================================================================= ======== Second, the extension example ----------------------------------- ---------------- 6) Matrix functions acting on two vector assume that we want to calculate the function f F (x, y) = x * exp (-X ^ 2 - y ^ 2) We have a series of X values, saved in the x vector, and we have a series of Y values. We want to calculate the f value each point on the vector x and the vector Y. In other words, we have to calculate the F value on the determined grid of the given vector X and Y. Using MeshGrid, we can copy X and Y to establish a suitable input vector. This function can then be calculated using the methods in Section 2. X = (-2: .2: 2); y = (-1.5: .2: 1.5) '; [x, y] = meshgrid (x, y); f = x. * Exp (-X. ^ 2 - y. ^ 2); If the function f has some properties, you can even use MeshGrid, such as f (x, y) = x * y, you can directly use vector external volume x = (-2: 2); Y = (-1.5: .5: 1.5); X '* y When establishing a matrix with two vector, in some cases, the sparse matrix can utilize storage space more effectively, and achieve effective algorithms. We will discuss more in more detail in Section 8. --------------------------------- ---------------------- 7) Sort, Set, and Count (ORDERING, SETTING, AND Counting Operations) in the examples discussed so far, The calculation of one element is independent of the other elements of the same vector. However, in many applications, the calculations you have to do may be closely related to other elements. For example, suppose you use a vector x to represent a collection. Do not observe the other elements of the vector, you don't know if an element is not a redundant element and should be removed. How to delete redundant elements without using a loop statement, at least now, is not a problem that can be solved. Solving such issues require considerable intelligence. The following introduces some of the available basic tools MAX Max Max minimum element SORT increment Sort Unique looks for the interaction of interior elements (remove the same element) DIFF differential operator [x (2) - x (1), x (3) - x ( 2), ... x (n) - x (n-1)] Find Find the index value of non-NAN elements UNION set and the INTERSECT collection set DIFF set poor setXOR set or continues our instance, eliminate the vector Excess elements. Note: Once the vector is sorted, any excess element is adjacent.

At the same time, it becomes zero at any equal adjacent element. This is what we can apply to the following strategies. We are now in the sorted vector, choose those differently non-zero elements. % Initially tried. Not right! X = sort (x (:)); Difference = DIFF (x); y = x (Difference ~ = 0); this is very close to the correct result, but we forgot the Diff function to return to the elements of the vector The number is less than the input vector. In our initial attempt, there is no difference in the last element. In order to solve this problem, we can add an element to the vector x prior to differentials, and make it different from the previous elements. An implementation method is to increase a nan. % Final version. X = sort (x (:)); Difference = DIFF ([x; nan]); y = x (Difference ~ = 0); We use (:) operation to ensure x is a vector. We use ~ = 0 operation without having to use a Find function, because the Find function does not return the index value of the NAN element, and the final element of the differential in our operation must be NAN. There is another way of implementation: y = unique (x); the latter is of course very simple, but the former is not useless, it is to practice the use of vectorization technology, and demonstrate how to write your own high-efficiency code . In addition, there is another role in the former: UNIQUE functions provide some additional features that exceed us, which may reduce the execution speed of the code. Suppose we don't just return a collection X, and know how many "copy" appear in each different element in the original matrix. Once we are sorted and differentiated, we can use find to determine the location of differential changes. The number of copies can be obtained by differential positions. This is the skill of "Diff of Find Of Diff". Based on the above discussion, we have:% find the redundancy in a vector xx = sort (x (:)); Difference = DIFF ([x; max (x) 1]); count = DIFF ([1; Difference]); y = x (find (difference)); Plot (Y, count) This figure draws the number of copies that appear in each of X. Note that we have avoided NAN because Find does not return the index value of the NAN element. However, as a special case, the number of replicas of NaN and INF can be easily calculated: count_nans = sum (isnan (x (:))); count_infs = sum (isinf (x (:)));

Another vectorization technique for seeking or counting the calculation is achieved with a square method of establishing a sparse matrix. This will also be discussed in detail in Section 9. ------------------------------------ ------------------ 8) Sparse Matrix Structures In some cases, you can use a sparse matrix to increase the efficiency of the calculation. If you construct a large intermediate matrix, usually easier. In some cases, you can fully use the sparse matrix structure to vectorize the code, and no large storage space is required for this intermediate matrix. Assuming in the previous example, you know that the agriculture of the collection Y is an integer, {k 1, k 2, ... k n}; 即, y = (1: n) k, for example, Such data may represent an index value of a palette. Then you can count the appearance of each element in the collector (build color histogram translator). This is a deformation of the "Diff of Find of Diff" techniques in the previous section.

Now let us construct a large M x N matrix A, where m is the number of elements in the original X vector, and n is the number of elements in the collection Y. A (i, j) = 1 IF x (i) = y (j) 0 OtherWise Removing Section 3 and Section 4, you may think we need to construct matrix A from X and Y. If of course, you can consume many storage spaces. We can do better because we know that there is only one value in the row of most elements in the matrix A, and there is only one value on each element in X. The following is a method of constructing a matrix (note y (j) = k j, according to the above formula): x = sort (x (:)); a = sparse (1: length (x), x k, 1 Length (x), n); now we ask the column of A to get the number of occurrences. Count = SUM (a); in this case, we don't have to clearly form sorting vector y, because we know Y = 1: N K in advance, (the key is to use data, "That is, use X control matrix A structure of a a). Since X is taken in a known range, we can construct a matrix more effectively. Suppose you want to multiply each column of a big matrix with the same vector. Using a sparse matrix not only saves space, but also more quickly than the method described in Section 5. The following is its work mode: f = rand (1024, 1024); x = rand (1024, 1);% to F All rows perform point-made multiplication. Y = f * diag (sparse (x));% of all columns of F. Y = diag (sparse (x)) * f; We make full use of matrix multiplication operators To perform large-scale operations and use a sparse matrix to prevent the time of time. -------------------------------------------------- ------ 9) Additional examples The following examples use some methods discussed in this technical manual, as well as other relevant parties. Try using TIC and TOC (or T = CPUTIME and CPUTIME-T) to see the speed of speed. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>> Double For cycle for calculating arrays.

Used Tools: A number of multiply optimization: a = MAGIC (100); b = pascal (100); for j = 1: 100 fork = 1: 100; x (j, k) = SQRT (A (J, K) )) * (B (j, k) - 1); End end Optimization: a = MAGIC (100); b = pASCAL (100); x = sqrt (a). * (B-1); >>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>> Establish a vector with a loop, the element depends on the tool used by the previous element: Filter, Cumsum, Cumprod optimization: a = 1; l = 1000; for i = 1: L A (i 1) = 2 * a (i) 1; END Optimization: L = 1000; a = filter ([1], [1 -2], Ones (1, L 1)); >>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Constructs only use addition or multiplication, you can use the cumsum or cumpprodu function.

Pre-optimization: n = 10000; v_b = 100 * ones (1, n); v_b2 = 100 * Ones (1, n); scalefactor = rand (1, n-1); for i = 2: n v_b (i) = V_B (i-1) * (1 ScaleFactor (I-1)); end for i = 2: N v_b2 (i) = v_b2 (i-1) 3; END Optimization: n = 10000; v_a = 100 * ones (1, n); v_a2 = 100 * ones (1, n); scalefactor = rand (1, n-1); v_a = cumprod ([100 1 scalefactor]); v_a2 = cumsum ([100 3 * Ones (1, n-1)]); >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>> Vector amount, each 5 elements are performed once: Tools: cumsum, vector index Optimization Before:% Use an arbitrary vector, x = 1: 10000; y = []; For n = 5: 5: Length (x) y = [y SUM (x (1: n))]; END Optimization (use pre-allocation): x = 1: 10000; YLENGTH = (Length X) - MOD (Length (x), 5)) / 5;% Avoid Using Zeros Command During Preallocation Y (1: YLENGTH) = 0; for n = 5: 5: Length (x) y (n / 5) = SUM (x (1: n)); END Optimization (use vectorization, no need for pre-allocation): x = 1: 10000; cums = cumsum (x); y = cums (5: 5: Length (x) ); >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>

Operation of a vector when an element is 0, repeat this element: Tool: Find, Cumsum, Diff task: We want to operate a vector made of non-zero values ​​and zero, require zero to become front of it Non-zero value. For example, we have to convert the following vector: a = 2; b = 3; c = 5; D = 15; E = 11; x = [a 0 0 0 B 0 0 0 0 0 0 D 0 E 0 0 0 0 0];: x = [aaaabbbccccddeeeeee]; solution (DIFF and CUMSUM are reverse function): Valind = Find (x); x (Valind (2: End)) = DIFF (x (Valind); x = cumsum (x); >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>> Elements of the vector to a specific location: Sparse Optimization Before:% the values ​​we are summing at designated indes value = [20 15 45 50 75 10 15 15 35 40 10];% the INDES Associated with the values ​​are summed cumulative component = [2 4 4 1 3 4 2 1 3 3 1]; Totals = Zeros (Max (INDICES), 1); for n = 1: Length (INDICES) TOTALS (INDES) )) = TOTALS (INDICES (N)) VALUES (N); END Optimization: INDICES = [2 4 4 1 3 4 2 1 3 3 1]; Totals = FULL (Sparse (INDICES, 1, VALUES)); Note: This method has opened up a new use of a sparse matrix. When you use the sparse command to create a sparse matrix, it is all values ​​assigned to the same index, rather than replacing existing values. This is called "vector accumulation", which is a mode of MATLAB to handle a sparse matrix.

============================================================================================================================================================================================================= ======================= 3, more resources ---------------------- ---------------------------------------- 10) Matrix Index and Computing The following matlab abstracts Discuss the matrix index. It provides more detailed information than the section 1 of this technical manual MATLAB Digest: Matrix Indexing in Matlab http://www.mathworks.com/company/digest/sept01/matrix.shtml The following instructions link will guide you how to use Matrix operation in matlab. Create, index, operation, array operation, matrix operation, and other subjects. MATLAB Documentation: getting start http://www.mathworks.com/access/helpdesk/help/techdoc/ Learn_Matlab / Learn_Matlab.shtml Peter Acklam is a Power User, he created a webpage to provide some tips in MATLAB array processing . Peter Acklam's Matlab Array Manipulation Tips and Tricks http://home.online.no/mtt/index.html -------------------------------------------------------------------------------------------------------------------------- ---------------------------------------- 11) Matrix Storage Management (Matrix Memory Management About the pre-allocation technology How to speed up more information on the speed of calculation, see the online solutions: 26623: How do i pre-allocate memory when useing matlab? Http://www.mathworks.com/support/solutions / Data/26623.SHTML The following technical manual is a wide range of guidelines for Matlab storage management: The Technical Support Guide to Memory Management http://www.mathworks.com/support/tech-notes/1100/1106. SHTML ----------------------------------------------- -------------- 12) Playing Maximizing Matlab Performance This technical manual is a general discussion of code vectorization, and many times, our purpose is to speed up

The speed of the code. Therefore, this section provides some additional resources, which involves how the code is up to the highest.

performance. Commonly used tips for acceleration code: 3257: How do i increase the spesed or peeds/data/support/solutions/data/3257.shtml compiles your code and calls it from Matlab 22512: What Are The Advantages in Using To MATLAB Compiler To Compile My M-Files? Http://www.mathworks.com/support/solutions/data/22512.shtml =============== ============================================================================================================================================================================================================= ===== Conclusion As described in this article, there are some general methods for the code vectorization and code speed, and there are some unconventional methods. As the last example of Section 9 (unique use of the sparse function) . The above discussion is far from exhausting all vectorization techniques in MATLAB. It is just a guidance of code vectorization ideas and theory.

-

※ Source: · BBS Shuimu Tsinghua Station Smth.edu.cn · [From: 166.111.185.48]

- ☆ Source:. Green bbs.dartmouth.edu. [From: mars.bbs@bbs.dartmou]

转载请注明原文地址:https://www.9cbs.com/read-7191.html

New Post(0)