1
votes

I know for a matrix say mat, if I want to delete all elements (element-wise) that satisfy certain condition, e.g. remove all zeros, this will do:

mat(mat == 0) = [];

But how can I do this sub-matrix-wise, i.e. remove matrix sub-matrix elements given conditions. As an example, data4d is a 4D matrix with size n1 x n2 x n3 x n4. If all the elements of the i-th (1=<i<=n4) sub-matrix of the fourth dimension, i.e. data4d(:, :, :, i) == zeros(n1, n2, n3), it will be removed, i.e. data4d(:, :, :, i) = [].

How can I do these without simple for loop? Both the following two version will not work:

data4d(data4d == zeros(n1, n2, n3)) = [];      // version 1
data4d(data4d == zeros(n1, n2, n3, 1)) = [];   // version 2
1

1 Answers

2
votes

One-liner using any and reshape:

data4D(:,:,:,~any(reshape(data4D,n1*n2*n3,n4),1)) = [];