Shift rows by different amounts

19 views (last 30 days)
Ellie
Ellie on 31 Jul 2015
Commented: Ellie on 31 Jul 2015
I have a N^2 x N^2 matrix where N = 4, and I wish to shift rows 1, 5, 9, and 13 by 0. Rows 2, 6, 10, 14 by 4. Rows 3, 7, 11, 15 by 8. Finally rows 4, 8, 12, 16 by 12. Ideally it would be a general code, as I plan to apply it to more than just this example. I have tried many things but to no avail. Any help would be appreciated. Thanks

Accepted Answer

Cedric
Cedric on 31 Jul 2015
Edited: Cedric on 31 Jul 2015
N = 4 ;
A = repmat( 1:N^2, N^2, 1 ) ; % Dummy example.
for k = 2 : N
A(k:N:N^2,:) = circshift( A(k:N:N^2,:), (k-1) * N, 2 ) ;
end
With that, the the original A is:
A =
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
and the final:
A =
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
13 14 15 16 1 2 3 4 5 6 7 8 9 10 11 12
9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8
5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
13 14 15 16 1 2 3 4 5 6 7 8 9 10 11 12
9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8
5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
13 14 15 16 1 2 3 4 5 6 7 8 9 10 11 12
9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8
5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
13 14 15 16 1 2 3 4 5 6 7 8 9 10 11 12
9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8
5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 4
I am not sure that the solutions that don't involve a FOR loop are more efficient ultimately, because the FOR loop has only N-1 iterations and no realloc or conversion to/from cell arrays. You'd have to profile every approach to be sure.
  2 Comments
Cedric
Cedric on 31 Jul 2015
PS: Andrei's BSXFUN-based solution can beat the loop though.

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 31 Jul 2015
  1 Comment
Ellie
Ellie on 31 Jul 2015
I have seen all of those and have attempted to modify them for my code but have been having issues.

Sign in to comment.

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!