Paste a value at a specific location in a Matlab vector or matrix

I am trying to insert a value into a vector at specific indices specified in another vector, and then shift the other values ​​accordingly.

eg.

Vector=[1 2 3 4 5] %vector of data
Idx=[2 4] %Indices at which to insert a value

Value to insert is X

NewVector=[1 X 2 X 3 4 5]

Is there an easy way to do this, preferably avoiding the loop?

+5
source share
2 answers
Vector=1:5;  
Idx=[2 4];
c=false(1,length(Vector)+length(Idx));
c(Idx)=true;
result=nan(size(c));
result(~c)=Vector;
result(c)=42

result =

     1    42     2    42     3     4     5

If you want the new values ​​to be inserted as in your deleted comment, do the following:

 c(Idx+(0:length(Idx)-1))=true;
+4
source

Here is a common function. The idea is the same as @Mark said:

   function arrOut = insertAt(arr,val,index)
      assert( index<= numel(arr)+1);
      assert( index>=1);
      if index == numel(arr)+1
          arrOut = [arr val];
      else
          arrOut = [arr(1:index-1) val arr(index:end)];
      end
   end

I have never heard of a built-in function for this.

+1
source

All Articles