MATLAB: Linear indexing for a portion of a matrix, notice that this is not trivial usage of sub2ind!

linear indexingsub2ind

I know that sub2ind can be used for converting matrix indexing to linear indexing. But the problem with sub2ind is that it requires pairs of row and column indices to be used. That does not cope with the normal indexing of matrices:
Let's say we have a matrix A=reshape(1:20,4,5), and then I want to address a portion of that matrix so that row indices are r=2:3 and column indices are c=3:4. That is easy, A(r,c), and that would give us 2×2 matrix containing values [10 14; 11 15].
Now, if I would like to convert this matrix indexing (r,c) to linear, I cannot do that simply with sub2ind because r and c are not pairs. Of course in this particular case linear indices can be get easily since the values itself happen to be linear indices, and actually we could get linear indices similarly for any matrix by doing a temporary matrix like A here and getting the values with matrix indexing A(r,c). However, that is not a nice way if we are dealing with really large matrices, because we need to create also very large temporary matrices just to get linear indices.
The best way that I have figured out is to use sub2ind, but first you have to create pairs from those row and column indices:
ind1=repmat(r',1,numel(c)); ind2=repmat(c,numel(r),1); sub2ind(size(A), ind1, ind2);
I am just wondering, have I missed some function in Matlab that could do this in a more sophisticated way? Of course, I could also just calculate the indices without using sub2ind at all but that would create ugly piece of code.

Best Answer

Well, it is trivial to convert subscripts into linear indices without sub2ind, it's just |rowindex + (colindex - 1) .* numberofrows), so with the new implicit expansion it's simply:
linindex = r(:) + (c - 1) .* size(A, 1)
In older version bsxfun replaces implicit expansion:
linindex = bsxfun(@sum, r(:), (c - 1) .* size(A, 1))