1

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.

User1772
  • 91
  • 8

2 Answers2

3
B = A;
B(all(mod(A,1)==0, 2), :) = [];
Xiangrui Li
  • 2,386
  • 2
  • 13
  • 17
2

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
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • Using `==` with floats is pretty risky isn't it? (http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab), you might be better off putting `B(all(abs(floor(B)-B) – Wolfie May 15 '17 at 16:17
  • 2
    @Wolfie If the number was originally integer to begin with, then the comparison should be fine. However, as soon as there is a whiff of floating-point in the number, then we should reject it regardless. In this case, the tolerance comparison I can get away with not doing. I would only compare within a tolerance if I am comparing equality with actual floating point numbers, but since we want to determine if a number is actually integer, we can skip. This is one of those times where doing equality actually works out for me, but in general you do compare within a tolerance as you have noted. – rayryeng May 15 '17 at 16:25
  • Thanks guys for your time. Both answers look similar but I will pretty much accept the 1st one. I will post just now a revised and more challenging (i would think) version of this question. – User1772 May 16 '17 at 10:49