2

I have two vectors, x and y that are defined(at random) as follows: x1=[1000 3000 5000 6000 4000 2000 500 0 -1000 -3000 -5000 -6000 -4000 -2000 -500 1 999 2999 4999]; y1=[5000 4999 4990 3500 2500 2499 2498 2497 2496 2495 2494 1000 -1000 -999 -998 -997 -996 -995 -994];

Following is the plot I obtained by simply typing in plot(x1,y1):

Plot of raw data

Is there a way to produce a smooth curve from the above data using the interp1 command? I have been told that I should use cubic splines to achieve the desired plot, however, since I am new to Matlab I am unaware of how to implement such a solution. Thanks in advance!

Edit: I have tried to implement it as follows, but I am getting a hideous looking plot! x1_temp=-6000:100:6000; pc=pchip(x1,y1,x1_temp); plot(x1,y1,'o',x1_temp,pc,'-');

How should I modify this code to produce the right plot?

Bilal Hussain
  • 73
  • 1
  • 6
  • 1
    Did you read the documentation for [`interp1`](http://www.mathworks.com/help/matlab/ref/interp1.html)? Under the [method section](http://www.mathworks.com/help/matlab/ref/interp1.html#inputarg_method) it shows you various spline options. Personally I recommend you start with `pchip` instead of cubic splines unless there is a compelling reason for you to use pure cubic splines. Read the docs, try it yourself, and ask again (WITH CODE!!!) if you get stuck. – Dan Mar 16 '16 at 08:11
  • 2
    You have a non monotonic vector x but a monotonic vector y. So you should not interpolate with `interp1(x1,y1,MyNewsPointsOnX,'pchip')` but use instead `interp1(y1,x1,MyNewsPointsOnY,'pchip')`. With `MyNewsPointsOnY = linspace(min(y1),max(y1),1000);` – obchardon Mar 16 '16 at 08:31
  • @Dan I have edited my original post to include my attempt at solving this problem. – Bilal Hussain Mar 16 '16 at 08:54
  • @obchardon What parameters do I include in the plot function to plot the required plot using the code which you've given? – Bilal Hussain Mar 16 '16 at 08:54

1 Answers1

3

I think you are confused about what you are interpolating. You should interpolate x1 and y1 separately, and afterwards plot them against each other. The following example produces a smooth curve:

x1=[1000 3000 5000 6000 4000 2000 500 0   -1000 -3000 -5000 -6000 -4000 -2000 -500 1   999 2999 4999];
y1=[5000 4999 4990 3500 2500 2499 2498 2497 2496 2495  2494  1000  -1000 -999 -998 -997 -996 -995 -994];

s = [0,cumsum(sqrt(diff(x1).^2+diff(y1).^2))]
N = length(s);

figure();
plot(x1,y1);
hold on

s_fine = interp1(linspace(0,1,N),s,linspace(0,1,5*N));
pcx=interp1(s,x1,s_fine,'spline');
pcy=interp1(s,y1,s_fine,'spline');
plot(pcx,pcy,'r-');
Nibor
  • 1,236
  • 9
  • 23
  • Thank you for your response. You were right, I was confused about what I should be interpolating. Your solution does what I wanted to do in my mind :) – Bilal Hussain Mar 16 '16 at 09:15