MATLAB: Combine 2 column matrix into 1 column matrix

columncombinematrixrow

I have a matrix A which contains x components, Note that A have multiple rows and columns.
Let's say
A=[ 1 2 3 4 0;
1.1 2.1 3.1 4.1 0;
1.2 2.2 3.2 4.2 0;
0 2.3 3.3 4.3 0;
0 2.4 3.4 4.4 0;
0 2.5 3.5 4.5 1.5;
0 2.6 3.6 4.6 1.6];
Now I want A to be
A=[ 1 2 3 4 ;
1.1 2.1 3.1 4.1 ;
1.2 2.2 3.2 4.2 ;
0 2.3 3.3 4.3 ;
0 2.4 3.4 4.4 ;
1.5 2.5 3.5 4.5 ;
1.6 2.6 3.6 4.6 ];
Note that the matrix is big so I cant use my vision to do so. I want to combine the one that has 0 as starting point (A(1,:)=0) to the one that has zero somewhere which is the first column and the condition is that the last point of first column is closer to the value of last column (you can see the last column has value of 1.5 which is closer to 1.2 that is why I combine them together)
Please helps. I am appreciated your opinions and helps.

Best Answer

If you want to merge non-zero elements of the last column into the first column, then you can use this:
A = [1.0, 2.0, 3.0, 4.0, 0;...
1.1, 2.1, 3.1, 4.1, 0;...
1.2, 2.2, 3.2, 4.2, 0;...
0, 2.3, 3.3, 4.3, 0;...
0, 2.4, 3.4, 4.4, 0;...
0, 2.5, 3.5, 4.5, 1.5;...
0, 2.6, 3.6, 4.6, 1.6];
X = A(:,end)>0;
A(X,1) = A(X,end);
A(:,end) = [];
This gives A as
A =
1.0 2.0 3.0 4.0
1.1 2.1 3.1 4.1
1.2 2.2 3.2 4.2
0 2.3 3.3 4.3
0 2.4 3.4 4.4
1.5 2.5 3.5 4.5
1.6 2.6 3.6 4.6