Pergunta

Essentially, if I have the following matrix:

[1, 2, 3 ,4, 10]

I need to explode it whilst interpolating, as follows:

[1, 1.5, 2, 2.5, 3, 3.5, 4, 7, 10].

Essentially, buff it up by filling in the average of the two surrounding values.

Say if I need to do this for n instead of adding just 1 value as we have here.

Foi útil?

Solução

You need to use interp1 with 'linear' interpolation method:

>> v = [1 2 3 4 10];
>> newNum = 13; % new number of elements in the "buffed" vector
>> iv = interp1( linspace(0,1,numel(v)), v, linspace(0,1,newNum) )
iv =
1.0000    1.3333    1.6667    2.0000    2.3333    2.6667    3.0000    3.3333    3.6667    4.0000    6.0000    8.0000   10.0000

Outras dicas

The inputs to interp1 are not always as trivial as they seem -- if you are trying to increase your sample rate to a certain amount without a phase shift, not just increase the number of elements while pinning the end points. You are requesting the latter condition, so that solution is already posted, but I think that it's also worth showing how to control the sample rate.

Take Shai's perfectly valid answer for increasing the number of elements without regard to the change in sample rate, for this case:

v = [1 2 3 4 10]; % 1x5
newNum = 10; % double the number
X =  linspace(0,1,numel(v));
Xi = linspace(0,1,newNum);
iv = interp1(X, v, Xi, 'linear')

This says we want to increase the number of elements from 5 to 10 -- double the number of elements -- while pinning the end points. Defining the initial sample rate for v to be 1, then what is the sample rate of iv?

>> iv = interp1( linspace(0,1,numel(v)), v, linspace(0,1,newNum) )
iv =
  Columns 1 through 8
    1.0000    1.4444    1.8889    2.3333    2.7778    3.2222    3.6667    4.6667
  Columns 9 through 10
    7.3333   10.0000
>> fs_v = X(2) - X(1) % even spacing
fs_v =
    0.2500
>> fs_vi = Xi(2) - Xi(1)
fs_vi =
    0.1111
>> fs_v / fs_vi 
ans =
    2.2500

More than double. Yeah, it's obvious when you think about it, but consider if this is what you want. You do get the ends pinned at iv(1)=1 and iv(end)=10, but you aren't specifying a change in sample rate.

Now say you want that exactly double sample rate increase. You can't get that and have the ends pinned at 1 and 10. To specify an Xi that gets you the right sample rate change:

scale = numel(v)/newNum; % i.e. 0.5
X = 1:numel(v);
Xi = (1:newNum)*scale + 0.5 * (1 - scale); % centered

The ends will not be pinned, but the sample rate will have doubled:

>> iv = interp1(X, v, Xi, 'linear', 'extrap')
iv =
  Columns 1 through 8
    0.7500    1.2500    1.7500    2.2500    2.7500    3.2500    3.7500    5.5000
  Columns 9 through 10
    8.5000   11.5000
>> (X(2) - X(1)) / (Xi(2) - Xi(1))
ans =
    2

At least in signal processing, you are usually after a change in sample rate not sample count.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top