imransydney
imransydney

Reputation: 65

How to get the values in between two points of a stair plot in matlab?

Is there any way to find the Y values between two X values using matlab from the attached plot? For example, if dx = 0.1, X = [0 5 10 12 13 14] and Y = [1 2 3 1 2.8 2], what would be the new values of Y with respect to that dx?

Please suggest.

Regards, Imran

stair plot

Upvotes: 1

Views: 2667

Answers (2)

imransydney
imransydney

Reputation: 65

I've found this following solution effective.

x = [0 5 10  12 13 14];
y = [1 2 3 1 2.8 2];

dx = 0.1;
last_index = 1; 

xi = [ min(x) : dx : max(x) ];

for j = 1:1:length(xi)
    while  (x(last_index) < max(x)) && ( xi(j) >= x(last_index + 1))
       last_index = last_index +1 ;
    end
   yi(j) = y(last_index);
end

[Xs, Ys] = stairs(xi, yi, 'ko-');

plot(Xs, Ys, 'r-')
hold on
plot(xi, yi, 'k-')

enter image description here

Upvotes: 0

hbaderts
hbaderts

Reputation: 14316

It is possible to solve this with the interp1 function, though of course not with the option linear. interp1 has three Nearest-Neighbor options:

  • nearest the nearest neighbor
  • next the next higher neighbor
  • previous the next lower neighbor

Thus, with the previous option, you can use interp1 and get the desired behavior. For comparison I added a plot of the interpolation and of the stairs plot. You'll see that the interpolated version doesn't have an infinite slope, as the step happens over dx=0.1.

X = [0 5 10 12 13 14];
Y = [1 2 3 1 2.8 2];
dx = 0.1;

xi = min(X):dx:max(X);
yi = interp1(X,Y,xi,'previous');

[xs,ys] = stairs(X,Y);
plot(xi,yi,'-b',xs,ys,'-r');

Stairs plot

(red: original stairs plot, blue: interpolated version)

Upvotes: 3

Related Questions