Search code examples
rjulianamissing-data

How to create NA matrix in Julia?


I am successful to create this NA matrix using this R code.

tree=matrix(NA,nrow=(4),ncol=(4))
tree

Output:- enter image description here

Edit:-

import Pkg
Pkg.add("Missings")
using Missings

Eurocall = function(S, T , K, r, sigma , N)
    
    # S : Spot Price
    # T : Time to Expire
    # K : Strike Price
    # r : Risk free rate of return
    # sigma : volatility of the asset
    # N : Length of the Binomial Tree
    
    deltaT=T/N
    u=exp(sigma*sqrt(deltaT))
    d=1/u
    p=(exp(r*deltaT)-d)/(u-d)
    
    tree = missings(Int,(N+1),(N+1))
  
    for i in 0:N
        tree[i+1,N+1]=max(0,(S*u^i*d^(N-i))-K)
    end
    
    for j in (N-1):0 
        for i in 0:j
            tree[i+1,j+1]=exp(-r*deltaT)*(p*tree[i+2,j+2]+(1-p)*tree[i+1,j+2])
        end
        
    end
    price=tree[1,1] 
    return(price)
end

Eurocall(10,10,11,0.05,0.1,10)

I wrote this code, but gives me this error

InexactError: Int64(1.2140275816016999)

How to fix this?


Solution

  • The missings function from Missings.jl is designed for this use-case:

    julia> using Missings
    
    julia> missings(Int, 3, 4)
    3×4 Matrix{Union{Missing, Int64}}:
     missing  missing  missing  missing
     missing  missing  missing  missing
     missing  missing  missing  missing
    

    (note that it is recommended to pass a type of elements that you want to later store in this martix)