Rearranging Data
I can think of a lot of functions that rearrange data in MATLAB. I've long suspected that not all of these are well-known, though some are clearly daily tools. Maybe it's time to be sure they get exposure.
Contents
My List of Functions for Rearranging Data
Here's my off the top of my head incomplete list.
Frequency of Use?
My guess is that circshift is one on the list that gets used least often. It's called a circular shift because elements that fall off at one end appear at the other end, wrapping around the values. Let's play with it to see what it can do. I'll use unique numbers in the sample matrix so we can follow them around.
A = reshape(1:16,4,4)'
A = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
From the help, I get to shift each dimension "up" or "down". Let's first just shift values in each column down by 2.
Adown2 = circshift(A,2)
Adown2 = 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8
Now let's shift just row values - to the right by 3.
Aright3 = circshift(A,[0 3])
Aright3 = 2 3 4 1 6 7 8 5 10 11 12 9 14 15 16 13
How about shifting left by 1?
Aleft1 = circshift(A,[0 -1])
Aleft1 = 2 3 4 1 6 7 8 5 10 11 12 9 14 15 16 13
We can see that shifting left by 1 is the same as shifting right by 3 when the number of columns is 4.
I can do a combination shift, with rows and columns.
Ad2l1 = circshift(A,[2 -1])
Ad2l1 = 10 11 12 9 14 15 16 13 2 3 4 1 6 7 8 5
What Do You Use?
What functions or techniques do you use to rearrange your data most often? Do you have a favorite function in this category that I didn't list?
Comments
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.