Programming |
Shifting the Location of Matrix Elements
The circshift
function shifts the elements of a matrix in a circular manner along one or more dimensions. Rows or columns that are shifted out of the matrix circulate back into the opposite end. For example, shifting a 4-by-7 matrix one place to the left moves the elements in columns 2 through 7 to columns 1 through 6, and moves column 1 to column 7.
Create a 5-by-8 matrix named A
and shift it to the right along the second (horizontal) dimension by three places. (You would use [0,
-3]
to shift to the left by three places):
A = [1:8; 11:18; 21:28; 31:38; 41:48] A = 1 2 3 4 5 6 7 8 11 12 13 14 15 16 17 18 21 22 23 24 25 26 27 28 31 32 33 34 35 36 37 38 41 42 43 44 45 46 47 48 B = circshift(A, [0, 3]) B = 6 7 8 1 2 3 4 5 16 17 18 11 12 13 14 15 26 27 28 21 22 23 24 25 36 37 38 31 32 33 34 35 46 47 48 41 42 43 44 45
Now take A
and shift it along both dimensions: three columns to the right and two rows up:
A = [1:8; 11:18; 21:28; 31:38; 41:48]; B = circshift(A, [-2, 3]) B = 26 27 28 21 22 23 24 25 36 37 38 31 32 33 34 35 46 47 48 41 42 43 44 45 6 7 8 1 2 3 4 5 16 17 18 11 12 13 14 15
Since circshift
circulates shifted rows and columns around to the other end of a matrix, shifting by the exact size of A
returns all rows and columns to their original location:
Shifting and Sorting Matrices | Sorting the Data in Each Column |
© 1994-2005 The MathWorks, Inc.