MATLAB: How to remove from a matrix only those columns whose all elements are either NaN or zeros

nan removal

I'm using R2016b:
An example of matrix:
A = [...
NaN 0.2200 0.2400 NaN
0.1400 0.2000 0.2600 NaN
0.1400 NaN 0.2600 NaN
0.1400 0.2200 0.2400 NaN
0.1400 0.2000 0.2600 NaN
0.1400 0.2000 0.2800 NaN
0.2200 0.6200 NaN NaN]
I want to exclude only column 4.
I tried ( from Andrei Bobrov on 25 Mar 2013):
out = A(all(~isnan(A),2),:); % for nan - rows
out = A(:,all(~isnan(A))); % for nan - columns
but they also remove all rows or columns with a single NaN element.
Thanks in advance.

Best Answer

  • I just find the solution for my question from Saman (on 23 Oct 2013);
    I guess it is problem related to the version of Matlab. I just had to change the "all" from Andrei Bobrov (25 Mar 2013) below, to "any", as suggested by Saman.
    Therefore:
    out = A(all(~isnan(A),2),:); % for nan - rows
    became
    out = A(any(~isnan(A),2),:); %for rows
    and
    out = A(:,all(~isnan(A))); % for nan - columns
    out = A(:,any(~isnan(A))); % for columns
    Thank you.