Insert elements before a specific value in vector
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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]'
0 Kommentare
Akzeptierte Antwort
Image Analyst
am 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 Kommentare
dpb
am 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.
Weitere Antworten (1)
dpb
am 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!