In MATLAB, there is a super simple yet powerful feature: flatten any n-dimensional array into a column vector in column-major order.
No matter what the original dimension of A is:
-
1 dimensional, 2 dimensional, 3 dimensional, N dimensional
-
4×4, 512×1024, 128×128×64
As long as you write: v = A(:); You will get a 1 column vector.
Since MATLAB‘s underlying storage is column-major (Fortran storage method), which we know as “column-major order”, the memory layout of A is:
A(:,1), A(:,2), A(:,3), … arranged sequentially
Therefore, (:) actually lays out the memory order completely, with zero overhead and very fast. Thus, (:) the value of “one-click flattening” lies in transforming complex multidimensional problems into 1D processing:
-
Modify a portion of elements in the matrix based on certain conditions;
-
Perform some operation on each element;
-
Batch process N×M data;
-
When writing algorithms, just think about “doing something for all samples” instead of dealing with multidimensional structures.
(:) is commonly paired with: reshape
If you flatten the matrix and want to reshape it back or change dimensions:
A1 = reshape(v, size(A));B = reshape(A, new_rows, new_cols);
In MATLAB, reshape does not change the underlying data, it only changes the “view” (how dimensions are interpreted), for example: A = reshape(1:8, [2 4]) has memory as [1 2 3 4 5 6 7 8], but is interpreted as:
1 3 5 72 4 6 8
Using (:) to flatten is essentially “changing the view back to one-dimensional”.
The number of elements used with reshape must match, otherwise it will throw an error, and the matrix after reshape is still constructed in column-major order. Understanding this, you will immediately know the result of all dimension transformations without trial.
Application Scenario 1: Modify the matrix based on conditions (without writing a for loop), for example, compressing all points exceeding a threshold to th, without needing a loop or find:
th = 0.5;A = rand(1024, 4096);v = A(:);v(v > th) = th;A2 = reshape(v, size(A));
Application Scenario 2: Perform operations on a certain dimension, but the algorithm is better suited for 1D writing, for example, normalizing all elements of a matrix, making global normalization of a multidimensional matrix very elegant:
A = rand(256, 1024);v = A(:);v = (v - min(v)) / (max(v) - min(v));A_norm = reshape(v, size(A));
Since the underlying linear data remains unchanged, reshape(A,3,2) merely interprets this segment of data in a new dimension without copying data, thus it is extremely fast (O(1) operation), so you need not worry about performance when performing complex data dimension transformations.
Once you understand this process of (:) and reshape, you will never forget it again!
Follow the WeChat public account “Software and Hardware Technology Development” to learn more related professional knowledge.