MATLAB: How to extract part of matrix on given dimension while this dimension is a variable

matrix manipulation

I want to build a function that can extract sub-matrix according to user input. Like the one shown below.
function newMatrix = extractMatrix(matrix,dim,index)
if dim == 1
newMatrix = matrix(index,:,:,...);
elseif dim == 2
newMatrix = matrix(:,index,:,...);
elseif
...
end
end
Since the length(size(matrix)) is also a variable, the conditional statement seems also not working here. What is the possible way for implementing such function?

Best Answer

function newMatrix = extractMatrix(matrix,dim,index)
id = repmat({':'},1,ndims(matrix));
id{dim} = index;
newMatrix = matrix(id{:});