Reputation: 293
I am looking for a way to delete empty matrices within a multidimensional array in MATLAB.
For example, I have a 4-D array such as:
N = 5;
Arr = zeros(2,2,4,N);
Lets assume only N = 2 and N = 4 have values (i.e the four 2x2 matrices in N = 1, 3 and 5 are zeros), how can I create another multidimensional array ArrFin(2,2,4,2) such that
ArrFin(2,2,4,1) = Arr(2,2,4,2);
ArrFin(2,2,4,2) = Arr(2,2,4,4);
I have tried to make the question quite general so that others can benefit from it as well but if I am not making much sense let me know.
Thanks in advance :)
Upvotes: 0
Views: 153
Reputation: 221514
Code
%%// Create data
Arr= rand(2,2,4,5);
Arr(:,:,:,[1 3 5]) = 0;
%%// Get new reduced matrix and check for its size
ArrFin = Arr(:,:,:,find(sum(reshape(sum(Arr,3),size(Arr,3),size(Arr,4)),1)));
size_check = size(ArrFin)
Output
size_check =
2 2 4 2
Upvotes: 0
Reputation: 293
Figured out quite a neat way to do it:
ArrFin = Arr(:,:,:,any(any(any(Arr,3))));
This picks out the non zero matrices and saves them into ArrFin.
Upvotes: 2