in MATLAB i wish to 开发者_运维技巧insert a value half way between every element in the vector
for example
v=[1,3,5,7,9]
i want to get
v=[1,2,3,4,5,6,7,8,9]
is there a quick way to do this?
A very simple, general way to do this is with interpolation, specifically the function INTERP1:
>> v = [1 3 5 7 9]
v =
1 3 5 7 9
>> v = interp1(v,1:0.5:numel(v))
v =
1 2 3 4 5 6 7 8 9
a = [1 3 5 7 9];
b = [2 4 6 8];
c = zeros(9,1);
c(1:2:9) = a; c(2:2:8) = b;
Since you just want the average of each two values to be inserted, you could do the following:
v = [1 3 5 7 9];
W = zeros(1,2*numel(v)-1);
W(1:2:end) = v;
W(2:2:end-1) = (W(1:2:end-2) + W(3:2:end))/2
If you want something else, take a look at interp1, which will allow for more advanced interpolation.
if diff(v) is a constant, like your example [1 3 5 7 9], you can do it like this:
>> v=[1 3 5 7 9]
v =
1 3 5 7 9
>> w=linspace(v(1),v(length(v)),2*length(v)-1)
w =
1 2 3 4 5 6 7 8 9
as the official help doc says:
y = linspace(x1,x2,n) generates n points. The spacing between the points is (x2-x1)/(n-1).
If diff(v) is not a constant ,like v=[1 3 6 8 10], you can first calculate the difference use
dv=diff(v)
then you can have w
w=ones(1,2*length(v)-1) %initialize
w(1:2:length(w))=v; % odd element
w(2:2:length(w)-1)=v(1:length(v)-1)+diff(v)*0.5 %even element
精彩评论