How to delete columns from 3D-array

Hello, i would like your help if possible. I have a 3D array. Lets say for example it is 2x5x2. The array is full. During the simulation it comes a time that the array has zeros in some columns. For example it has zeros in the 1st dimension for columns 2 and 4. How do i delete the zeros and then how can i shift the after value to take the zeros place and final replace the empty values by zeros.
Example:
Q(:,:,1) = 1 1 1 1 1; 2 2 2 2 2;
Q(:,:,2) = 3 3 3 3 3; 4 4 4 4 4;
During Simulation:
Q(:,:,1) = 1 0 1 0 1; 2 0 2 0 2;
Q(:,:,2) = 3 3 3 3 3; 4 4 4 4 4;
I want this to happen:
Q(:,:,1) = 1 1 1 0 0; 2 2 2 0 0;
Q(:,:,2) = 3 3 3 3 3; 4 4 4 4 4;
Thank you in advance

Answers (1)

If the order of the nonzero elements isn't of significance or they're matching as the example then
>> Q(:,:,1) = [1 0 1 0 1; 2 0 2 0 2];
Q(:,:,2) = [3 3 3 3 3; 4 4 4 4 4];
>> Q(:,:,1)=sort(Q(:,:,1),2,'descend');
>> Q
Q(:,:,1) =
1 1 1 0 0
2 2 2 0 0
Q(:,:,2) =
3 3 3 3 3
4 4 4 4 4
>>

2 Comments

Thank you very much !!
So if this is a workable solution, please ACCEPT the answer to, at minimum, let others know...

Sign in to comment.

Categories

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

Asked:

on 6 Nov 2016

Commented:

dpb
on 6 Nov 2016

Community Treasure Hunt

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

Start Hunting!