# How to remove null matrices from a multidemensional array?

1 view (last 30 days)
Luciano Campos on 10 Jun 2021
Commented: Luciano Campos on 10 Jun 2021
Hi, I'd like to remove all null matrices from a 3-dimensional array.
Suppose I have the following 3x3x5 multidimensional matrix, where the first and the third matrices are null. ¿How can I remove the null matrices such that the resulting multidimensional matrix is 3x3x3?
Matrix(:,:,1) =
0 0 0
0 0 0
0 0 0
Matrix(:,:,2) =
-0.6842 0.8145 0.7498
0.8353 1.5250 0.0004
-1.5288 0.4317 1.3572
Matrix(:,:,3) =
0 0 0
0 0 0
0 0 0
Matrix(:,:,4) =
1.4528 0.0807 0.3814
-0.1675 -0.7258 1.0134
-0.1237 -0.3353 0.6182
Matrix(:,:,5) =
1.2482 0.1368 0.8166
0.8369 1.8682 -0.6398
-1.0774 -1.1223 0.8522

Max Heiken on 10 Jun 2021
Edited: Max Heiken on 10 Jun 2021
You could identify the all zero pages and remove them like this:
Matrix(:, :, ~any(Matrix, [1, 2])) = [];
Luciano Campos on 10 Jun 2021
Thanks Max! This works just fine!
Best,

Steven Lord on 10 Jun 2021
Use the capability of the any function to accept a vector of dimensions over which to operate.
z = zeros(3);
r = @() rand(3);
M = cat(3, z, r(), z, r(), r())
M =
M(:,:,1) = 0 0 0 0 0 0 0 0 0 M(:,:,2) = 0.5431 0.5116 0.6777 0.3478 0.2512 0.9538 0.9902 0.5727 0.1137 M(:,:,3) = 0 0 0 0 0 0 0 0 0 M(:,:,4) = 0.5013 0.7561 0.0333 0.7886 0.6559 0.0514 0.8881 0.1103 0.9360 M(:,:,5) = 0.0428 0.5918 0.6839 0.4889 0.5199 0.2981 0.1230 0.2536 0.2200
whichPagesHaveData = any(M, [1 2])
whichPagesHaveData = 1×1×5 logical array
whichPagesHaveData(:,:,1) = 0 whichPagesHaveData(:,:,2) = 1 whichPagesHaveData(:,:,3) = 0 whichPagesHaveData(:,:,4) = 1 whichPagesHaveData(:,:,5) = 1
M2 = M(:, :, whichPagesHaveData)
M2 =
M2(:,:,1) = 0.5431 0.5116 0.6777 0.3478 0.2512 0.9538 0.9902 0.5727 0.1137 M2(:,:,2) = 0.5013 0.7561 0.0333 0.7886 0.6559 0.0514 0.8881 0.1103 0.9360 M2(:,:,3) = 0.0428 0.5918 0.6839 0.4889 0.5199 0.2981 0.1230 0.2536 0.2200
isequal(M(:, :, 4), M2(:, :, 2)) % page 4 of M is page 2 of M2 by the way we constructed M
ans = logical
1
Luciano Campos on 10 Jun 2021
Thanks!

R2021a

### Community Treasure Hunt

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

Start Hunting!