Insert elements before a specific value in vector

4 vues (au cours des 30 derniers jours)
K G
K G le 7 Jan 2017
Commenté : dpb le 9 Jan 2017
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]'

Réponse acceptée

Image Analyst
Image Analyst le 7 Jan 2017
Wow, so complicated. Obviously you've never heard of the strrep() trick. Simply call strrep() like this:
% Create row vector, not column vector, sample data.
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]
% Replace 0 with [1.5, 0]
out = strrep(twtt, 0, [1.5, 0])
If you want a column vector, you can simply transpose out.
  3 commentaires
K G
K G le 9 Jan 2017
I would now like to put a velocity value (1472) into another vector, rms_vel, at every corresponding element to each 1.5 value in twtt_new/out. Do you know of a simple way to do this using the index position of each 1.5 in twtt_new?
dpb
dpb le 9 Jan 2017
Well, if you had the find indices, it should be pretty obvious what to do with them I'd think...but you don't need find at all--
rms_vel(twtt_new==1.5)=1472;
Look up "logical addressing" in the doc; extremely powerful topic.

Connectez-vous pour commenter.

Plus de réponses (1)

dpb
dpb le 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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by