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

 采纳的回答

idx=repmat({':'},1,ndims(M));
idx{dim}=1:size(M,dim)-N;
M2=M(idx{:})

2 个评论

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

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by