Remove rows in variable dimension

2 visualizaciones (últimos 30 días)
Martin Hultman
Martin Hultman el 16 de Sept. de 2019
Comentada: Matt J el 16 de Sept. de 2019
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

Respuesta aceptada

Matt J
Matt J el 16 de Sept. de 2019
idx=repmat({':'},1,ndims(M));
idx{dim}=1:size(M,dim)-N;
M2=M(idx{:})
  2 comentarios
Martin Hultman
Martin Hultman el 16 de Sept. de 2019
Brilliant! I had no idea you could use cell arrays to index like that!
Thanks!
Matt J
Matt J el 16 de Sept. de 2019

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by