0
votes

I have a vector with different values. Some of the values are zeros and sometimes they even come one after another. I need to plot this vector against another vector with the same size but I can't have zeros in it. What is the best way I can do some kind of interpolation to my vector and how do I do it? I tried to read about interpolation in mat-lab but I didn't understand good enough to implement it. If it's possible to explain it to me step by step I will be grateful since I'm new with this program.

Thanks

1
I dont get this: do you want to replace zeros or are there vectors of different lengths? - Lucius II.
I want to replace the zeros with other values but in a smart way so when i will do my plot it will be close to what it was supposed to be. - Maayan
but interpolation can give you zeros as well... - Lucius II.
what if you would just skip zero-values? - Lucius II.
If you are going to interpolate a vector containing zeros, and especially one after another, it will be very likely for the interpolation to entail zeros as well. Maybe you could explain why you want to do this a bit more? - Fraukje

1 Answers

5
votes

Starting from a dataset consisting of two equal length vectors x,y, where y values equal to zero are to be excluded, first pick the subset excluding zeros:

incld = y~=0;

Then you interpolate over that subset:

yn = interp1(x(incld),y(incld),x);

Example result, plotting x against y (green) and x against yn (red):

enter image description here

edit

Notice that, by the definition of interpolation, if terminal points are zero, you will have to take care of that separately, for instance by running the following before the lines above:

if y(1)==0, y(1) = y(find(y~=0,1,'first'))/2; end
if y(end)==0, y(end) = y(find(y~=0,1,'last'))/2; end

edit #2

And this is the 2D version of the above, where arrays X and Y are coordinates corresponding to the entries in 2D array Z:

[nr nc]=size(Z);
[X Y] = meshgrid([1:nc],[1:nr]);
X2 = X;
Y2 = Y;
Z2 = Z;
excld = Z==0;
X2(excld) = [];
Y2(excld) = [];
Z2(excld) = [];
ZN = griddata(X2,Y2,Z2,X,Y);

ZN contains the interpolated points.

In the figure below, zeros are shown by dark blue patches. Left is before interpolation, right is after: enter image description here