Insert value at a specific spot in matlab vector or matrix

前端 未结 2 1079
青春惊慌失措
青春惊慌失措 2021-01-03 04:01

I\'m trying to insert a value to a vector at specific indices, specified in another vector, and then displacing the other values accordingly.

E.g.



        
相关标签:
2条回答
  • 2021-01-03 04:11
    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 wanted the new values inserted as in your deleted comment, do this:

     c(Idx+(0:length(Idx)-1))=true;
    
    0 讨论(0)
  • 2021-01-03 04:11

    Here is a general 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.

    0 讨论(0)
提交回复
热议问题