Joe
Joe

Reputation: 453

Delete columns if condition is matched in all but one cell in MATLAB

I have a matrix A of size 13472x30974. In the first row, there is always a value (from 1 to 30974). I would like to delete the columns, if all other values in the specific column are NaN.

I can delete the columns, if I separate the first row from the rest of the matrix, yet I won't be able to combine the two matrices then (because they will be of different size).

B = A(:, ~all(isnan(A)));

I guess that using any instead of all won't return the desired output neither, as some columns might contain values with NaN and real values.

So how could I address the part of the matrix from 2:13472, yet delete from 1:13472?

Upvotes: 0

Views: 78

Answers (1)

Wolfie
Wolfie

Reputation: 30046

You can just use isnan on the 2:end rows

B = A( :, ~all(isnan(A(2:end, :))) )
  • Runs the isnan on A excluding the first row - A(2:end, :)
  • Outputs all rows of A - A(:, ___ )

If you just want to remove the matching columns, instead of assigning to B then use

A( :, all(isnan(A(2:end, :))) ) = [];

Upvotes: 2

Related Questions