Question

i have a n-dimensional matrix from which i want the n-2 -dimensional submatrix

For example:

if i have a matrix A that is 6x5x4x3x2, i want to get for example the matrix

B = A(1,:,:,:,2);

This is easy if the amount of dimensions is fixed, but how can i do this for variable dimensions without having to handle a specific case for each number of dimensions?

Bad:
n = length(size(A));
if (n == 2)
  B = A(1,2)
else if (n == 3)
  B = A(1,:,2);
else if (n == 4)
  B = A(1,:,:,2);
else if (n == 5)
  B = A (1,:,:,:,2);

 ...

 Good:
 B=A(1,<some cool operator/expression>,2);
Was it helpful?

Solution

Thanks to the link provided in the comment, i was able to solve it like this:

n = ndim(A);
if (n <= 2)
   B = A(1,2);
else
   colons = repmat({':'},[1 n-2]);
   B = A(1,colons{:},2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top