Interpolation with matlab

别来无恙 提交于 2019-12-11 20:49:12

问题


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:


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:



来源:https://stackoverflow.com/questions/18715639/interpolation-with-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!