Insert elements before a specific value in vector

조회 수: 4 (최근 30일)
K G
K G 2017년 1월 7일
댓글: dpb 2017년 1월 9일
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]'

채택된 답변

Image Analyst
Image Analyst 2017년 1월 7일
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
K G
K G 2017년 1월 9일
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 2017년 1월 9일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

dpb
dpb 2017년 1월 7일
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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by