首页 > matlab > 在MATLAB中从单元矩阵中删除NaN

在MATLAB中从单元矩阵中删除NaN (Remove NaN from cell matrix in MATLAB)

2019-02-28 matlabcell

问题

我有一个包含数值和NaN的单元格矩阵。如何删除NaN值并“修剪”我的矩阵。

例如,我有以下矩阵:

A = { 1, 12, NaN; 1 ,4, NaN; 1 , 2 , NaN ; NaN, NaN, NaN; 1, 2, NaN };

我想删除NaN并调整矩阵大小以获得此矩阵。可以没有循环吗?(使用矢量化)

A = [ 1, 12; 1, 4; 1, 2; 1, 2];

解决方法

A = { 1, 12, NaN; 1 ,4, NaN; 1 , 2 , NaN ; NaN, NaN, NaN; 1, 2, NaN };
A = cell2mat(A) ;   % convert the given cell to matrix         
[m,n] = size(A) ;   % get size of the matrix 
A(sum(isnan(A),2)==n,:) = [] ;  % remove rows with all NaN's in a row 
[m,n] = size(A) ;   % get updated size of A 
A(:,sum(isnan(A),1)==m) = [] ;  % remove columns with all NaN's in a column 

结果

 A = [1    12
      1     4
      1     2
      1     2]

问题

I have a cell matrix containing numeric values and NaN. How can I remove the NaN values and "trim" my matrix.

For example I have the following matrix:

A = { 1, 12, NaN; 1 ,4, NaN; 1 , 2 , NaN ; NaN, NaN, NaN; 1, 2, NaN };

I would like to remove the NaN and resize the matrix to have this matrix. Can it be done without loop ? (using vectorisation)

A = [ 1, 12; 1, 4; 1, 2; 1, 2];

解决方法

A = { 1, 12, NaN; 1 ,4, NaN; 1 , 2 , NaN ; NaN, NaN, NaN; 1, 2, NaN };
A = cell2mat(A) ;   % convert the given cell to matrix         
[m,n] = size(A) ;   % get size of the matrix 
A(sum(isnan(A),2)==n,:) = [] ;  % remove rows with all NaN's in a row 
[m,n] = size(A) ;   % get updated size of A 
A(:,sum(isnan(A),1)==m) = [] ;  % remove columns with all NaN's in a column 

Result

 A = [1    12
      1     4
      1     2
      1     2]
相似信息