Shift rows by different amounts

23 次查看(过去 30 天)
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

采纳的回答

Cedric
Cedric 2015-7-31
编辑:Cedric 2015-7-31
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 个评论
Cedric
Cedric 2015-7-31
PS: Andrei's BSXFUN-based solution can beat the loop though.

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2015-7-31
  1 个评论
Ellie
Ellie 2015-7-31
I have seen all of those and have attempted to modify them for my code but have been having issues.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by