function sub = ind2subv(siz, ndx)
% IND2SUBV Like the built-in ind2sub, but returns the answer as a row vector.
% sub = ind2subv(siz, ndx)
%
% e.g., sub = ind2subv([2 2 2], 1:8) returns
% sub(1,:) = [1 1 1], sub(2,:) = [2 1 1], sub(3,:) = [1 2 1], ..., sub(8,:) = [2 2 2]
% That is, the leftmost digit toggle fastest.

n = length(siz);
if n==0
  sub = ndx;
  return;
end
cp = [1 cumprod(siz)];
ndx = ndx - 1;
for i = n:-1:1 % i'th digit
  sub(i,:) = floor(ndx/cp(i))+1;
  ndx = rem(ndx,cp(i));
end
sub = sub';
