# using CG when A is function handle

**URL:** <https://discourse.julialang.org/t/using-cg-when-a-is-function-handle/12434>\
**Category:** Specific Domains\
**Tags:** question\
**Created:** [July 17, 2018, 12:04pm UTC](https://discourse.julialang.org/t/using-cg-when-a-is-function-handle/12434 "2018-07-17T12:04:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rajiv](https://avatars.discourse-cdn.com/v4/letter/r/b3f665/32.png) [@Rajiv](https://discourse.julialang.org/u/Rajiv)\
**Post date:** [July 17, 2018, 12:04pm UTC](https://discourse.julialang.org/t/using-cg-when-a-is-function-handle/12434/1 "2018-07-17T12:04:19Z")

</div>

I am trying to use CG from the IterativeSolvers.jl solver. I have “A” as a matrix-free operator but it is build using nested functions. Is linear map works for “A” inside of which there are several function calls? I do not find an example in the test folder where I can setup CG solver when A is a function handle.

---

<div class="post-metadata">

**Author:** ![mohamed82008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mohamed82008/32/18171_2.png) [@mohamed82008](https://discourse.julialang.org/u/mohamed82008)\
**Post date:** [July 17, 2018, 1:19pm UTC](https://discourse.julialang.org/t/using-cg-when-a-is-function-handle/12434/2 "2018-07-17T13:19:43Z")

</div>

Here is how to do it. I am assuming you are on Julia v0.6.

```julia
using IterativeSolvers

struct MyLinearMap{TM}
	A::TM
end

# You will need to define these functions for your type

Base.A_mul_B!(c, L::MyLinearMap, b) = A_mul_B!(c, L.A, b)
Base.:*(L::MyLinearMap, b) = L.A*b
Base.eltype(L::MyLinearMap) = eltype(L.A)
Base.size(L::MyLinearMap, i::Int) = size(L.A, i)

# Let's test it 

A = sprand(1000, 1000, 0.01)
A = A + A' + 30I

op = MyLinearMap(A)
norm(cg(op, op*ones(1000)) - ones(1000))
#2.979898645518114e-5

```

---

<div class="post-metadata">

**Author:** ![Rajiv](https://avatars.discourse-cdn.com/v4/letter/r/b3f665/32.png) [@Rajiv](https://discourse.julialang.org/u/Rajiv)\
**Post date:** [July 18, 2018, 2:10am UTC](https://discourse.julialang.org/t/using-cg-when-a-is-function-handle/12434/4 "2018-07-18T02:10:12Z")

</div>

thanks a lot
