在MATLAB中从单元矩阵中删除NaN

问题描述 投票:0回答:2

我有一个包含数值和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];
matlab cell
2个回答
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]

0
投票

乍一看,我没有看到(自动)保留矩阵的“形状”(尺寸)的方法。对于转换和提取,有一个简单的解决方案:

B = cell2mat(A)
B =

     1    12   NaN
     1     4   NaN
     1     2   NaN
   NaN   NaN   NaN
     1     2   NaN

B = B(~isnan(B))
B =

    1
    1
    1
    1
   12
    4
    2
    2

我将进一步考虑(自动)调整大小。

© www.soinside.com 2019 - 2024. All rights reserved.