2.3 Insert a number at specific position in a vector or list

The problem is to insert a number into a vector given the index.

Mathematica

vec={1,2,3,4}; 
vec=Insert[vec,99,3]; 
vec
 

Out[11]= {1,2,99,3,4}
 

 

Matlab

A=[1 2 3 4]; 
A=[ A(1:2) 99 A(3:end) ]
 

A = 
     1     2    99     3     4
 

 

Julia

A=[1,2,3,4]; 
A=insert!(A,3,99)'
 

1Œ5 adjoint(::Vector{Int64}) with eltype Int64: 
 1  2  99  3  4
 

 

Fortran

program f  implicit none 
  REAL(4), ALLOCATABLE :: A(:) 
  A=[1,2,3,4]; 
  A=[A(1:2), 99.0, A(3:)] 
  Print *,A 
end program f
 

>gfortran -std=f2008 t2.f90 
>./a.out 
 1.0000000 2.0000000 99.000000 
          3.0000000 4.0000000
 

 

Maple

v:=Vector[row]([1,2,3,4]); 
v:=Vector[row]([v[1..2],99,v[3..]]);
 

Or Using <> notation

v:=<1|2|3|4>; 
v:=<v(1..2)|99|v(3..)>;
 

v :=[ 1 2 99 3 4]
 

 

Python

Python uses zero index.

import numpy as np 
b=np.array([1,2,3,4]) 
b=numpy.insert(b,2,99) 
b
 

   Out[86]: array([ 1,  2, 99,  3,  4])