Reputation: 149
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
Upvotes: 0
Views: 893
Reputation: 5073
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):
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:
Upvotes: 5