MATLAB: Remove rows or cols whose elements are all NaN

colsnanrows

I have a matrix A:
A = [1 2 3 4 NaN;
NaN NaN NaN NaN NaN;
1 2 NaN 4 5;
1 NaN 3 4 5];
and what I just want to is:
A = [1 2 3 4 NaN;
1 2 NaN 4 5;
1 NaN 3 4 5];
Currently I'm using the follwoing:
method = 1;
A = A'; % transposing is just for convenience
if method == 1
A = A(:, ~isnan(nanmean(A))); % nanmean throws NaN if all elements are NaN
elseif method == 2
A = A(:, sum(~isnan(A)) ~= 0);
end
A = A'; % re-transpose
However, I think nanmean is for statistical purpose and not for matrix manipulation. Moreover, actually I have much much much larger matrix. Thus, such operation might require longer computational time.
And I don't think all(isnan(A)) or all(~isnan(A)) is appropriate in some special cases.

Best Answer

your_mat = A(all(isnan(A),2),:);