Removing zeros from a m x n x p matrix.

I have a matrix, let's call it "A", that is 6 x 3 x 5 x 5. In my code, I separate each "block" of the matrix so that I now have five 6 x 3 x 5 matrix, A1, A2, A3, A4, A5.
Now in A4, A4(:,:,4) and A4(:,:,5) are both all zeros. How would I remove these from the matrix, leaving A4 as a 6 x 3 x 3 matrix, with non-zero values only? I've tried to use all() but I get an error: "Index exceeds matrix dimensions".
For example if B is m by n, I could use
B(all(B==0,2),:) = [] to remove zero rows. Similarly, I'd like to remove the elements along the all A(:,:,p) that are zero
I'd like to have a way to remove the zero matrices even if I don't know which ones are zeros. For instance it could be any one of the value of "p" for A4(:,:,p). (If I run the program once, it could be 1 5 3, and another time it could be 2 and 4, so merely specifying the rows by hand won't work for more than one run.)

 Accepted Answer

A=rand(6,3,5,5)
for k=1:size(A,4)
B{k}=A(:,:,:,k)
end
A4=B{4}
A4(:,:,4:5)=[]

6 Comments

Thank you, but I need a way to remove the zero matrices even if I don't know which ones are zeros. For instance it could be any one of the values of "p" for A4(:,:,p), and sometimes more than one.
idx=[];
for k=1:size(A4,3)
a=A4(:,:,k)
if all(~any(a))
idx=[idx k]
end
end
A4(:,:,idx)=[]
David
David on 5 Mar 2013
Edited: David on 5 Mar 2013
Any way to do it without any looping or conditional and just all() and any()?
idx=find(arrayfun(@(x) all(~any(A4(:,:,x))),1:size(A4,3)))
A4(:,:,idx)=[]
Thanks very much.
David, I learned in this forum that in most cases, a for loop is much faster then arrayfun or cellfun

Sign in to comment.

More Answers (1)

A4(:,:,[4 5]) = [];

1 Comment

David
David on 5 Mar 2013
Edited: David on 5 Mar 2013
This would work if I knew beforehand that 4 and 5 were zero, but what if I don't know? Let's say that the next time I run it, it's 1 and 3. Could I set it up using either any() or all() so that it just removes those zeros?

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!