Remove rows in variable dimension

Is there a way to remove the N last rows of a variable dimension dim in a multi-dimensional matrix. For example, if M is a 4x4x4x4 matrix, N=2,and dim=2 I want the result to be a 4x2x4x4 matrix. If N=1 and dim=4 I want a 4x4x4x3 matrix, and so on. Kind of like an inverse of cat. The problem is that I don't know the number or size of dimensions beforehand, or which dimension to remove from.
My current solution is to use the following switch statement. I have assusmed that I will never work with more than 8 dimensions, and then this works fine. I'm just wondering if there is a better way, as this is (in my opinion) very ugly and not at all modular enough to be satisfying.
switch(dim)
case 1
M2 = M(1:(end-N),:,:,:,:,:,:,:);
case 2
M2 = M(:,1:(end-N),:,:,:,:,:,:);
case 3
M2 = M(:,:,1:(end-N),:,:,:,:,:);
case 4
M2 = M(:,:,:,1:(end-N),:,:,:,:);
case 5
M2 = M(:,:,:,:,1:(end-N),:,:,:);
case 6
M2 = M(:,:,:,:,:,1:(end-N),:,:);
case 7
M2 = M(:,:,:,:,:,:,1:(end-N),:);
case 8
M2 = M(:,:,:,:,:,:,:,1:(end-N));
end

 Risposta accettata

Matt J
Matt J il 16 Set 2019
idx=repmat({':'},1,ndims(M));
idx{dim}=1:size(M,dim)-N;
M2=M(idx{:})

2 Commenti

Brilliant! I had no idea you could use cell arrays to index like that!
Thanks!

Accedi per commentare.

Più risposte (0)

Categorie

Prodotti

Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by