MATLAB: How to arrange or matrix columns, depending on the total sum that has the columns

matrix manipulation

Hi, I need to arrange a matrix A to look like matrix B.
Matrix A generate new positions at every iteration, so the positions are not fixed.
If there is a column in A (in this case, column 3) that has sum=0, and after it has column that sum=1 (column 4), I want column 4 to move to column 3. Then column 5 move to column 4 and the last column is the one that keeps the sum=0 column.
This is a sequencing problem, so my desire is to have a smooth sequence.
What is the best way to do this?
Thanks!
if true
A = [0 1 0 0 0;
1 0 0 0 1;
0 0 0 1 0;
0 0 0 0 0;
0 0 0 0 0];
B = [0 1 0 0 0;
1 0 0 1 0;
0 0 1 0 0;
0 0 0 0 0;
0 0 0 0 0];
end

Best Answer

Do
s = sum(A,1);
p = find(s(1:end-1)==0&s(2:end)==1);
B = A(:,[setdiff(1:size(A,2),p),p]);
(Corrected)