MATLAB: Convert subscripts to linear indices with dynamic matrix size

convert subscripts to linear indicesMATLAB

Hi all,
I have a matrix with a dynamic size, e.g. M x N. Each row of the matrix indicates subscripts of an element in a N-D matrix.
Do you know how to convert the subscript matrix into a linear index vector without listing the subscripts of every dimension as in sub2ind function?
Thanks!

Best Answer

% Generate random array of nd-indexes
sz=[3 4 5 6];
m = 10;
n = length(sz);
SUBIDX=ceil(sz.*rand(m,n));
% Method 1, with sub2ind
LINIDX1 = zeros(m,1);
for k=1:size(SUBIDX,1)
subidxk = num2cell(SUBIDX(k,:));
LINIDX1(k) = sub2ind(sz,subidxk{:});
end
LINIDX1
% Method 2, not using sub2ind, NOTE: no error check for overflow
p = cumprod([1 sz(1:end-1)]);
LINIDX2 = (SUBIDX-1)*p(:)+1
% Method 3, for-loop on dimension
LINIDX3 = 0;
for k=n:-1:1
LINIDX3 = LINIDX3 * sz(k) + (SUBIDX(:,k)-1);
end
LINIDX3 = LINIDX3 + 1