Removing NaN values ​​from the array and left shift

I have a 34 x 1096 array that has NaN values.

 A = 
 NaN    0.2500     NaN    0.3750       NaN
 NaN    0.1100     NaN    0.4310     0.1250
 NaN    0.1250    0.2500  0.3750     0.4310

I want too

 A = 
0.2500   0.3750       NaN     NaN       NaN
0.1100   0.4310     0.1250    NaN       NaN
0.1250   0.2500     0.3750   0.4310     NaN     

What is an easy way to do this?

+4
source share
3 answers

An easy way would be to use a for loop with ~isnanfor each line, for example:

B=NaN(size(A));
for n=1:size(A,1)
    B(n,1:sum(~isnan(A(n,:))))=A(n,~isnan(A(n,:)));
end    

B =
0.2500    0.3750       NaN       NaN       NaN
0.1100    0.4310    0.1250       NaN       NaN
0.1250    0.2500    0.3750    0.4310       NaN

then you can assign A=Bif you need ... and yes, it can be done without a for loop, but why bother in this case?

+1
source
[~, jj] = sort(isnan(A), 2);
B = A(bsxfun(@plus, (1:size(A,1)).', (jj-1)*size(A,1)));
+2
source

the code

 A = [
 NaN    0.2500     NaN    0.3750       NaN
 NaN    0.1100     NaN    0.4310     0.1250
 NaN    0.1250    0.2500  0.3750     0.4310]

[M,N] = size(A)
[~,col1] = sort(~isnan(A),2,'descend')

row1 = repmat(1:M,N,1)'; %%//'
restructured_indices = sub2ind(size(A),row1(:),col1(:))
A = reshape(A(restructured_indices),M,N)

Output

A =
    0.2500    0.3750       NaN       NaN       NaN
    0.1100    0.4310    0.1250       NaN       NaN
    0.1250    0.2500    0.3750    0.4310       NaN
+1
source

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


All Articles