User1772
User1772

Reputation: 91

How do i remove matrix rows that contain all integers?

Assuming I have a 7x3 matrix which contains both integers and non-integers. What i would want is to remove all rows containing only integers. An example is as follows:

A = [1, 1, 2
     2, 1.5, 1
     3, 1.5, 2
     1, 2, 1
     2, 2.5, 1
     3, 2.5, 1
     1, 3, 2];

My output should be:

B = [2, 1.5, 1
     3, 1.5, 2
     2, 2.5, 1
     3, 2.5, 1];

Please, how can I possibly achieve this? Thank you.

Upvotes: 1

Views: 95

Answers (2)

rayryeng
rayryeng

Reputation: 104555

Another way to do this would be to take the floor of the matrix and compare this with the original one. You would thus find those rows that are equal between the two and remove those.

B = A;
B(all(floor(B) == B, 2), :) = [];

The logic behind this is pretty simple. floor truncates the matrix so that only the whole numbers remain (that is without the decimal point). You would then element-wise compare this with the original matrix. Those values that were originally integer would still be integer once you take the floor and those elements that are integer would thus give you a true result. Those elements that are floating-point would give you false. We then use all to look at each row independently and see if all columns for a row are true meaning that the entire row consists of integers. We would thus find those rows and remove them from the final matrix to produce the desired result.

We thus get:

>> format long g;
>> B

B =

                         2                       1.5                         1
                         3                       1.5                         2
                         2                       2.5                         1
                         3                       2.5                         1

Upvotes: 2

Xiangrui Li
Xiangrui Li

Reputation: 2436

B = A;
B(all(mod(A,1)==0, 2), :) = [];

Upvotes: 3

Related Questions