MATLAB: How to delete one element of the third dimen in a 4d matrix

3d4ddelete elementsMATLABmatrixresize

Hi,
i have a 4d Matrix with the size of [i j n k] target size is [i j n-1 k] and i want to delete always the smalest of the n elements. I made it like this:
sz = size(Matrix);
Matrix_neu = zeros(sz - [0 0 1 0]);
[~, I] = min(Matrix,[],3);
for i = 1:sz(1)
for j = 1:sz(2)
for k = 1:sz(4)
temp = true(1,sz(3));
temp(I(i,j,1,k)) = false;
Matrix_neu(i,j,:,k) = Matrix(i,j,temp,k);
end
end
end
but i think there is a more elegant and faster way isn't it?
Regards Markus

Best Answer

If you know the minima are uniquely attained, you could do something like this,
[m,n,p,q]=size(Matrix);
Matrix = reshape( permute(Matrix,[3,2,1,4]), p,[] );
idx=bsxfun(@gt, Matrix, min(Matrix,[],1));
Matrix_neu=ipermute( reshape( Matrix(idx), [p-1,n,m,q]) , [3 2 1 4]);