kirikoumath
kirikoumath

Reputation: 733

circshift columns of array by different shift size

I'm trying to do the following with arrayfun and circshift

s_dfp = magic(4);
s_hh1p = circshift(s_dfp(:,1),[1 -1]);
s_hh2p = circshift(s_dfp(:,2),[1 -2]);
s_hh3p = circshift(s_dfp(:,3),[1 -3]);
s_hh4p = circshift(s_dfp(:,4),[1 -4]);
HH = [s_hh1p s_hh2p s_hh3p s_hh4p];

s_dfp =

    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1


HH =

     4    14    15     1
    16     2     3    13
     5    11    10     8
     9     7     6    12

Each column is shifted by its column number. I would like to do this for arbitrary size.

Thanks in advance.

Upvotes: 1

Views: 734

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112699

To shift each column down by a number of entries equal to the column number:

[R, C] = size(s_dfp);
row = mod(bsxfun(@plus, (0:R-1).', -(1:C)), R) + 1; %'// shifted row indices
ind = bsxfun(@plus, row, 0:R:numel(s_dfp)-1); %// corresponding linear indices
HH = s_dfp(ind);

Example:

s_dfp =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

gives

HH =
     4     7    10    13
    16    14     6     8
     5     2    15    12
     9    11     3     1

Upvotes: 1

Related Questions