Removing NaN Elements from a Matrix

There is one NaN element in the line, I want to remove it.

A=[NaN 1 2; 3 NaN 4; NaN 5 6]; 

Required Result:

 [1 2; 3 4; 5 6] 
+4
source share
3 answers
 A = [NaN 1 2 ; 3 NaN 4; NaN 5 6] sz = size(A); B = reshape(A', size(A,1)*size(A,2), 1); B(isnan(B)) = []; B = reshape(B, sz(2)-1, sz(1))' 
+6
source

I thought this could be done on one line, but I was wrong. See Solution below:

Given (the added line helps me debug my indexing below):

 >> A = [NaN 1 2 ; 3 NaN 4; NaN 5 6; 7 8 NaN] A = NaN 1 2 3 NaN 4 NaN 5 6 7 8 NaN 

Then:

 >> Atrans = A'; >> B = reshape( Atrans(~isnan(Atrans)) ,[],size(Atrans,2))' B = 1 2 3 4 5 6 7 8 

By the way, Matlab's Italoma for performing a simple logical check in an array in a logical indexing operation is very common and incredibly useful. Archetypal example:

 >> x(x>0) %This returns a 1D column vector of all values of x %which are greater than 0, regardless of the initial %size of x. Multidimensional inputs are unwrapped %column-first 

Everything else above is handling size and size.

+2
source

Here it is - note that the code is not reliable. It assumes that indeed every line has a NaN element.

Despite the fact that it is not a vectorized solution, it has other advantages - like clean code.

 for i=1:size(A,1) x = A(i,:); x(isnan(x)) = []; B(i,:) = x; end 

IN

B =

 1 2 3 4 5 6 
0
source

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


All Articles