Search code examples
matlaboutliers

Matlab - How to remove outliers from a set of 2D points?


My question has two parts:

  1. I have two 1D arrays containing X and Y values. How can I create another 1D array where each element is a 2D point?
  2. How to remove outliers from the resulting array?

For example, something like this:

x = [1 3 2 4 2 3 400];
y = [2 3 1 4 2 1 500];
xy = [[1 2] [3 3] [2 1] [4 4] [2 2] [3 1] [400 500]];
result = rmoutliers(xy, 'mean');

The result should look like:

result = [[1 2] [3 3] [2 1] [4 4] [2 2] [3 1]]

My goal is to remove outlier points in a set of points like this (the points forming a line at the top):

enter image description here


Solution

  • First create an nx2 matrix.

    x = [1 3 2 4 2 3 400]';
    y = [2 3 1 4 2 1 500]';
    xy = [x, y]
    

    Now xy takes the following form:

    xy = 
         1     2
         3     3
         2     1
         4     4
         2     2
         3     1
       400   500
    

    Now pass this matrix through rmoutliers:

    result = rmoutliers(xy);
    

    The value of result should now be:

    result =
         1     2
         3     3
         2     1
         4     4
         2     2
         3     1
    

    As a note, there is no way to make a 1D array where each point has 2 dimensions because... well then you have a 2-dimensional array by definition. Keep things simple and just build a 2-dimensional matrix from the start!