Summing elements at the end of a column with elements at the beginning of the next row

Viewed 41

Suppose I have the following matrix in Matlab:

A = [1 2 3
     4 5 6
     7 8 9
     3 2 1
     6 5 4]; 

Now imagine that I'd like to have a vector as follows:

v = [1 4 7 3 6 0 0 0 0 0 0] + [0 0 0 2 5 8 2 5 0 0 0] + [0 0 0 0 0 0 3 6 9 1 4];

That is, I'd like to read A by columns but I want that the 2 last elements of each column are summed with the first 2 elements of the next column (the last element of the 1st column with the 2nd element of the 2nd column, the 4th element of the 1st column with the 1st element of the 2nd columns, etc.)

Now, if A has very large dimensions, how could I do this process efficiently without a loop?

Thanks for your answers.

2 Answers

You can create a sparse matrix from the zero padded columns and sum along its second dimension:

s = size(A);
f = s(1) - 2;
r = (1:s(1)).' + (0:f:(s(2) - 1) * f);
c =  repmat(1:s(2), s(1), 1);
M = sparse(r, c, A);
v = full(sum(M, 2));

A small variation of @rahnema1's answer, which exploits the fact that sparse automatically adds values at coincident indices:

A = [1 2 3; 4 5 6; 7 8 9; 3 2 1; 6 5 4]; % data matrix
N = 2; % shift to be applied to each column
s = size(A);
f = s(1) - N;
r = (1:s(1)).' + (0:f:(s(2) - 1) * f);
v = full(sparse(1, r, A));

Equivalently, you can use accumarray instead of sparse, replacing the last line by

v = accumarray(r(:), A(:)).';
Related