3 CommentsOldest to Newest
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:
% 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)
Keep up the interesting posts!
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