MATLAB: Hello, how can i remove zero from an array and leave the array in the same form? thanks

arraymatrix

for example,
for Aij !=0
bil = Aij
i,j,l,++
A =
1 0 2 6 0
0 3 4 0 0
5 0 2 7 4
to become
b=
1 2 6 NaN
3 4 NaN NaN
5 2 7 4

Best Answer

Edit 20170214: added comments as requested
>> A = [1,0,2,6,0;0,3,4,0,0;5,0,2,7,4]
A =
1 0 2 6 0
0 3 4 0 0
5 0 2 7 4
>> S = size(A);
% sort the zero elements of A to be last, C contains the column indices of the sorted data:
>> [~,C] = sort(A==0,2);
% define row indices:
>> R = repmat((1:S(1)).',1,S(2));
% use the row and (sorted) column indices to create linear indices, sort A using the linear indices:
>> B = A(sub2ind(S,R,C));
% remove all columns that contain only zeros:
>> B(:,all(B==0,1)) = [];
% replace zeros with NaN:
>> B(B==0) = NaN
B =
1 2 6 NaN
3 4 NaN NaN
5 2 7 4