How to get rid of NaN when moving cells up the column in matlab

I have a relatively large matrix (800'000 x 1'000) that contains NaN at the end of some columns, and I need to get rid of them by moving through each cell. When I delete NaN, the next cell should move up. I cannot move the values ​​of the next column to cells after values ​​other than NaN for the column on the right. It is important that the number of rows remains the same as the original matrix (which I am correcting), but the number of columns will obviously change.

Here is an example on a smaller A1 4x5 matrix:

A1 = [
     1     5     8     9    11
     2     6   NaN    10    12
     3     7   NaN   NaN    13
     4   NaN   NaN   NaN  NaN  ]

I need A1 to become:

A2 = [
     1     5     9    13
     2     6    10    NaN
     3     7    11    NaN
     4     8    12    NaN   ]

A1 (1,3) = 8 A2 (4,2) = 8, A1 (1,4) = 9 A2 (1,3) = 9, A1 (2,4) = 10 A2 (2,3) = 10 . - 4, 4. NaN , " ", , ( ) , NaN. , :

A3 = [
     1     5     9 
     2     6    10  
     3     7    11  
     4     8    12  ]

A1 (~ isnan (A1)), -, , , , A3 .

A1 A3?

+4
3

, NaN, . :

reshape(A1(isfinite(A1)),4,[])

, , , , .

, , , - :

A2=A1(isfinite(A1))
A3=reshape(A2(1:(4*floor(length(A2)/4))),4,[])
+2

- , , .

vals = A1(~isnan(A1));
A2 = NaN(size(A1));
A2(1:length(vals)) = vals;
A3 = A2(:,~any(isnan(A2)));
0
n = size(A1,1); %// number of rows
A1 = A1(~isnan(A1)); %// linearize to a column and remove NaN's
A1 = A1(1:floor(numel(A1)/n)*n); %// trim last values if needed
A1 = reshape(A1,n,[]); %// put into desired shape
0

Source: https://habr.com/ru/post/1530735/


All Articles