Search code examples
matlabmatrix-indexing

Extract elements of matrix from a starting element and size


Sorry about the bad title, I'm struggling to word this question well. Basically what I want to do is extract elements from a 2d matrix, from row by row, taking out a number of elements (N) starting at a particular column (k). In for loops, this would look like.

A = magic(6);
k = [2,2,3,3,4,4]; % for example
N = 3;
for j = 1:length(A)
    B(j,:) = A(j,k(j):k(j)+N-1);
end

I figure there must be a neater way to do it than that.


Solution

  • You could use bsxfun to create an array of indices to use. Then combine this with the row numbers and pass it to sub2ind.

    inds = sub2ind(size(A), repmat(1:size(A, 1), 3, 1), bsxfun(@plus, k, (0:(N-1))')).';
    B = A(inds);
    

    Or alternately without sub2ind (but slightly more cryptic).

    B = A(bsxfun(@plus, 1:size(A,1), ((bsxfun(@plus, k, (0:(N-1)).')-1) * size(A,1))).');