Reputation: 7
I have a large matrix data which are based on row and columns, I want to delete all those columns which contain all values are 0
in MATLAB.
Upvotes: 0
Views: 53
Reputation: 65430
You can use all
with a second input to check which columns have all zeros. This will return a logical
array that is true
when all rows of a given column satisfy a condition and false
otherwise. You can then use the inverse of the result as a logical index to select only the columns that don't satisfy this criteria
data = data(:, ~all(data == 0, 1));
Alternately, you could use any
in a similar way. any
will return a logical array that is true
when there is any row in a column that satisfies the condition and false
otherwise.
data = data(:, any(data ~= 0, 1));
This one can be simplified even further though since internally, any
will cast data
as a logical
value turning any non-zero value into true
and any zero value into `false.
data = data(:, any(data, 1));
If you are working with floating point numbers, you'll want to use a very small epsilon rather than comparing numbers directly to 0
data = data(:, ~all(abs(data) < eps, 1));
data = data(:, any(abs(data) > eps, 1));
Upvotes: 1