Using MATLAB linspace between every element in an array

ぐ巨炮叔叔 提交于 2020-01-11 09:55:10

问题


Using MATLAB, I would like to linearly interpolate between every point in an array.

Using interpolate will do it in a non-linear fashion. What I want to do is similar to producing low-pass filter coefficients.

I have come up with a solution, but I would like to avoid using for loops:

a=[0 0 1 0 0]; %Input matrix
N=5; %Number of points to be added
b=[];
for i=1:length(a)-1
    b=[b linspace(a(i),a(i+1),N)];
end

Is it possible to do this without a loop?


回答1:


You can create a linear spline with the points in a as control points. After that you can specify as many points as you want from a beginning interval to an ending interval. As what Raab70 said, you can use interp1. interp1 can be called in the following way (using linear interpolation):

out = interp1(x, y, xp, 'linear')

x are the x values and y are the y values for the control points. xp are the points you want to evaluate the function at. Because you don't explicitly have x values and you just want the y values, you can create a dummy vector that goes from 1 up to L where L is how many points are in your output data. This dummy vector is for your x values. After, specify y as your output data. In this case, it is the array of a. Next, you need to specify where you want to sample along the curve. Because you want to introduce 5 points in between each space, you will have in total 5*4 + 5 = 25 points all together. 5 points per "slot", and there are 4 slots all together. You also include the 5 points that were from your original output data. To create these 25 points, simply perform linspace from 1 up to 5 and specify that you want 25 points in between this interval. This should perfectly capture the control points (the dummy values of 1,2,3,4,5) as well as the values that you want to use to interpolate in between each of the control points.

As such, try something like this:

N = 5; %// Number of points to introduce in between each control point
y = [0 0 1 0 0]; %// Your output data
L = numel(y); %// Size of output data. Cache so we don't have to keep typing in numel(y)
x = 1:L; %// Dummy vector
xp = linspace(1, L, N*(L-1) + N); %// Create points to interpolate. N*(L-1) + N is also just N*L
out = interp1(x, y, xp, 'linear'); %// Generate interpolated array

out thus gives me:

out =

Columns 1 through 9

     0         0         0         0         0         0         0    0.1667    0.3333

Columns 10 through 18

0.5000    0.6667    0.8333    1.0000    0.8333    0.6667    0.5000    0.3333    0.1667

Columns 19 through 25

     0         0         0         0         0         0         0


来源:https://stackoverflow.com/questions/23525001/using-matlab-linspace-between-every-element-in-an-array

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