function [r,c] = ndx3d(siz,i,j,k)
%NDX3D	Index into 3-D matrix packed in a 2-D matrix.
%	ELEM = NDX3D([M N P],I,J,K) returns the element position ELEM
%	of the (i,j,k) elements of a M-by-N-by-P matrix which is
%	stored in a (M*N)-by-P matrix.  For example, the three M-by-N
%	matrices A1,A2,A3 are packed into a 2-D matrix using
%	  A = [A1(:) A2(:) A3(:)];
%	If length(I) is m, LENGTH(J) is n, and LENGTH(K) is p,
%	then ELEM will be an m-by-n-by-p matrix.
%
%	[R,C] = NDX3D([M N P],I,J,K) returns the row and column 
%	position of the (i,j,k) element as stored in the normal
%	2-D matrix of size (M*N)-by-P.
%
%	To specify all the elements along one dimension use ':'.
%	For instance, NDX3D([3 5 4],2:3,':',3:4) returns the
%	elements for the 2-by-5-by-2 matrix.
%
%	See also ELEM3D, MESHGRID, SLICE.

%	Clay M. Thompson 11-3-92
%	Copyright (c) 1992 by The MathWorks, Inc.
%	$Revision: 1.7 $  $Date: 1993/09/03 14:36:52 $

if isstr(i), i = 1:siz(1); end
if isstr(j), j = 1:siz(2); end
if isstr(k), k = 1:siz(3); end

if isempty(i) | isempty(j) | isempty(k), r = []; c = []; return, end

if any( (i<0) | (i>siz(1)) ), error('Index I out of range.'); end
if any( (j<0) | (j>siz(2)) ), error('Index J out of range.'); end
if any( (k<0) | (k>siz(3)) ), error('Index K out of range.'); end

if nargout==2
  [jj,ii] = meshgrid(j,i);
  r = ii(:) + (jj(:)-1)*siz(1);
  c = k(:);

else
  [jj,ii,kk] = meshgrid(j,i,k);
  r = ii + (jj-1)*siz(1) + (kk-1)*prod(siz(1:2));

end

