Remove redundant points on plot

Viewed 140

I trying to plot a function which has millions of points. Therefore it is not possible to plot the function as it would crash my computer. However, the entire plot consists of "elbows" in that more than 1 variable cannot change at a time.

Consider the following matrix

a = [1 2 3 4 4 4 4];
b = [1 1 1 1 2 3 4];

These points make the following figure when using plot(a,b)

enter image description here

However, upon closer inspection, I can reduce my plot vectors down to

a = [1 4 4];
b = [1 1 4];

and get the same plot.

My question is: what is a vectorized way to automatically remove every redundant point. I could easily loop through and search for points to remove but this would be expensive. I have tried using combinations of diff and cumsum to do this to no avail. I only have straight lines and right angles in the plot so I do not have to worry about anything of the form ax+b

2 Answers

You can use a diff(diff(a))~=0, or equivalently diff(a, 2)~=0, to get a perhaps cleaner looking solution. This will work whether you plug a or b into the diff function.

mat = [true, diff(a, 2)~=0, true];
a(mat)
 ans =
     1     4     4
b(mat)
 ans =
     1     1     4

Guess I'll answer my own question in case anyone else needs this. Basically what I'm doing is doing the first diff on each matrix to see if the values are changing between each element. The second diff looks for a change. Because we're looking for elbows, we end up switching from true on the x-axis to true on the y-axis. This is the point we're looking for. Then we add on the ends. From there we only keep the true elements for our original matrix.

mat = [true diff(logical(diff(a))-logical(diff(b))) true];
a(mat)
[1     4     4]
b(mat)
[1     1     4]

I'm open to alternative suggestions as this is very hacky.

Related