Matlab:如果矩阵中包含多个特定数量的NaN值,如何删除矩阵中的所有列

时间:2013-03-02 18:28:29

标签: matlab matrix

我想删除所有具有超过一定数量NaN的列(比如5个NaN)。有没有办法没有循环呢?

2 个答案:

答案 0 :(得分:2)

不需要循环:

matFixed = MAT( :, sum( isnan( MAT ) ) <= 5);

一步一步:

nanMat = isnan(MAT); % convert MAT to logical with 1 indicating value is a NAN
nNanInCol = sum(nanMat); %compute the number of NANs in each col
colIdx = nNanInCol <= 5; % determine which columns are "valid"
matFixed = MAT(:, colIdx); % create new matrix using only the good columns of MAT

答案 1 :(得分:0)

非常简单:

%# define a matrix with NaNs
A = rand(10); %# 10x10 array
A(A<0.5) = NaN; %# each column contains on average 5 NaNs

%# count NaNs
nanCt = sum(isnan(A),1);

%# remove columns with too many NaNs
A(:,nanCt > 5) = [];