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

 채택된 답변

Matt J
Matt J 2019년 9월 16일

0 개 추천

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

댓글 수: 2

Martin Hultman
Martin Hultman 2019년 9월 16일
Brilliant! I had no idea you could use cell arrays to index like that!
Thanks!
Matt J
Matt J 2019년 9월 16일

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2019년 9월 16일

댓글:

2019년 9월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by