DAZone
DAZone

Reputation: 15

Extend vector in Matlab

I have a simple doubt, I want to extend in Matlab a vector:

a = [1 2 3 4 n];

In the following way:

b = [1 1.5 2 2.5 3 3.5 4 ... n];

This means, make a new vector with the double size of the previous one, but the new added values must be the mean of the previous and the next number.

Any idea of a loop to solve this problem?

Upvotes: 0

Views: 444

Answers (3)

Suever
Suever

Reputation: 65430

You can use linear interpolation (interp1) to solve this problem. Using the a vector, we can interpolate values at and between each of the elements.

a = [1 2 3 4 17];

b = interp1(a, linspace(1, numel(a), numel(a) * 2 - 1), 'linear');
%   1   1.5   2   2.5   3   3.5   4   10.5   17 

Explanation

What this does is assumes that you have a function f(x) where x = [1 2 3 4 5] and f(x) = a. What you ultimately want is the value of f(x) where x = [1 1.5 2 2.5 3 3.5 4 4.5 5] (i.e. the values and the values in-between values. If we use the 'linear' option, then the in-between values will be replaced with the average of it's neighbors.

Upvotes: 1

Mendi Barel
Mendi Barel

Reputation: 3677

without any assumption on order

a = [1 2 5 9 17];
d=[diff(a),0]
a2=[a;a+d/2]
b=a2(1:end-1)

Upvotes: 0

rahnema1
rahnema1

Reputation: 15837

A possible solution

b(1:2:2*numel(a)-1)=a
b(2:2:end) = a(1:end-1)+diff(a)/2

Upvotes: 2

Related Questions