Insert elements before a specific value in vector
Show older comments
I have a vector of time, twtt. At every point where twtt(i)=0 (except for i=1) I need to insert a value, 1.5, before it. For example:
twtt=[0 0.25 0.5 0 0.25 0.26 0.5 0 0.1 0.25 0.4 0.5 0.6 0 0.25 0.5]';
should become
twtt_new=[0 0.25 0.5 1.5 0 0.25 0.26 0.5 1.5 0 0.1 0.25 0.4 0.5 0.6 1.5 0 0.25 0.5 1.5]';
The distance between 0's is variable so I cannot use a predictor.
The code I have currently is almost there but I cannot figure out where I am going wrong. Any help would be appreciated.
Code:
idx=find(twtt(2:end)==0); % To exclude 0 at i=1
twtt_new=zeros(length(twtt)+length(idx),1); % New vector is larger
first_val=idx(1);
counter=1;
j=1;
for i=1:length(twtt)-1
if j>length(idx);
break;
else
if i~=idx(j) && i<first_val;
twtt_new(i)=twtt(i);
elseif i~=idx(j) && i>first_val;
twtt_new(i+counter)=twtt(i);
elseif i==idx(j) && i==first_val;
twtt_new(i)=1.5;
j=j+1;
elseif i==idx(j) && i>first_val;
twtt_new(i+counter)=1.5;
j=j+1;
counter=counter+1;
end
end
end
Resultant and wrong twtt_new produced by code above:
twtt_new=[0 0.2500 1.5000 0 0 0.2500 0.2600 1.5000 0 0 0.1000 0.2500 0.4000 0.5000 1.5000 0 0 0 0]'
Accepted Answer
More Answers (1)
dpb
on 7 Jan 2017
Alternate ways, but a "deadahead" route is
iz=[find([nan twtt(2:end)]==0) length(twtt)]; % locations except first of zero keeping length
t=[];
for i=length(iz)-1:-1:1 % work from end backwards...
t=[[1.5 twtt(iz(i):iz(i+1))] t];
end
t=[twtt(1:iz(1)-1) t]; % add first section before first zero
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!