Non-circular shift in Matlab?

13,889

Solution 1

No, there isn't. If there were, it would be under "Sorting and Reshaping Arrays" in the main Matlab function list.

http://www.mathworks.com/help/matlab/array-manipulation.html

So, as you say, you'll need to write your own. You could probably do a pretty concise implementation by writing the shift logic along dimension 1 and using shiftdim in a loop to rotate the matrix to effectively apply it to all the requested shift dimensions and then back to the original dimensional orientation.

Solution 2

You can probably use circshift and set the shifted space to zero manually. For example, if you had to shift a matrix left and have zeroes padded to the right, you'd do something like:

shifted_mat = circshift(mat, -1, 2);
shifted_mat(:, end) = 0;

The -1 and 2 in circshift denote the magnitude and the direction of shift respectively. You can use this for shifting up and down too.

Share:
13,889
Suzan Cioc
Author by

Suzan Cioc

Not to be offended

Updated on June 04, 2022

Comments

  • Suzan Cioc
    Suzan Cioc almost 2 years

    Matlab has circshift which shifts matrix circularly, i.e. putting shifted out elements to opposite side.

    Is there a function which shifts matrix with copying last values or padding new space with zeros? Like bitwise shift in C/C++ does?

    UPDATE

    I know I can write function myself.