Stuart’s MATLAB Videos

Watch and Learn

Inserting data into a vector in MATLAB 3

Posted by Doug Hull,

If you want to insert a data point into an existing series, you may need to insert a corresponding data point in another vector in the same place. You could do that with logical indexing and concatenation of vectors as shown in this video.

3 CommentsOldest to Newest

Matt Fig replied on : 1 of 3
Hello Doug, Great topic! I have often come across situations just like this, only it usually involves inserting multiple values rather than a scalar. Here is a generalization of what you posted:
 
% Initial vectors.
A = 1:10;
B = A.^2;
% Values to insert
Ai = rand(1,3)*10;
Bi = Ai.^2;
% Insertion process.
[NewA,I] = sort([A,Ai]);
NewB = [B Bi];
% The new vectors
NewA
NewB = NewB(I)
 
Another, related challenge is to insert values into a vector based on the index positions in a second vector. This one comes up all the time on Answers and the Newsgroup. Here is one solution to this problem:
 
A = 1:10;  % Initial vector
B = [30 50 100];   % Values to insert
Bi = [3 5 10];  % Index of current A where the values are to be inserted.

Anew = zeros(1,length(A)+length(B));
Anew(Bi+(0:length(Bi)-1)) = B;
Anew(~Anew) = A
 
Keep up the interesting posts!
Anand replied on : 2 of 3
Matt, Your code is quite nifty if you don't have to insert 0s into A. A better solution is: A = 1:10; % Initial vector B = [30 0 100]; % Values to insert which include a Zero Bi = [3 5 10]; % Index of current A where the values are to be inserted. Anew = zeros(1,length(A)+length(B)) + NaN; Anew(Bi+(0:length(Bi)-1)) = B; Anew(isnan(Anew)) = A Thanks for the tip though! Now it works quite generically unless of course, you WANT to insert a NaN. But why don't my code blocks look as nice as yours ???
Bruce Stott replied on : 3 of 3
Doug, Matt and Anand, This was a big help! Thank you very much! I have been trying to insert a '0' into a string at different points. My string size varies but the general values do not. Here is an example of what I was able to do with your examples. P='1x1_21x1_13x2_4x15_1x1_2x3'; lenP = length(P); locUs = find(P=='_'); locX = find(P=='x'); %Want to modify string so all addresses are the same size %i.e. '01x13_'. So will insert '0's before the single digit numbers. pathOrg = sort([locX locUs lenP+1 ]); %Vector that shows all x's, '_'s, & the end+1. %Vector used to decide if need to insert a '0'. decisionVec = [locX(1) pathOrg(2:length(pathOrg)) - pathOrg(1:length(pathOrg)-1)]; viBelow3 = (decisionVec 0) - viBelow3(viBelow3 > 0); %Points to insert at. % P is automatically converted to a number vector when needed. newP = zeros(1,lenP + length(insertPts));% %Build a vector of the right size. newP(insertPts+(0:length(insertPts)-1)) = '0'; %Insert '0' where needed. Note:'0'~=0. newP(newP==0) = P; %Insert P in for the zeros. newP = [char(newP) '_']; disp(['Original string = ',P]) disp(pathOrg) disp(decisionVec) disp(viBelow3) disp(insertPts) disp(['New path = ',newP])