Chang
Chang

Reputation: 83

Can I put multiple functions into one matrix using iteration in Julia?

I am new to Julia and trying to see whether I can put different functions as an element of a Mtrix

I constructed a matrix B (2x2)

And I want to put function,for example, x^1 + 1x as a (1,1) element, x^1 + 2x as a (1,2) element, x^2 + 1x as a (2,1) element and x^2 + 2x as a (2,2) element

I was planning to do something like as below but couldn't find a way to implement this. Is it possible to make such Matrix?

B = Array{Function}(undef,2,2)
agrid = 1:1:2
dgrid = 1:1:2
for(i_a,a) in enumerate(agrid)
for(i_d,d) in enumerate(dgrid)
B[i_a,i_d](x) = x^a+d*x
end
end

The reason I want to construct this matrix is to solve the following model.

I need to solve the equation with two variables 'm' and 'n' given 'a' and 'd'.

And I thought if I have a matrix consisting of each function with all possible combinations of 'a' and 'd'(in the sample code, the possible combination would be (1,1) (1,2) (2,1) (2,2)), then it would be easier to solve the model at once.

Any help will be appreciated.

Thank you.

Upvotes: 1

Views: 164

Answers (1)

BatWannaBe
BatWannaBe

Reputation: 4510

Yes it's possible. You could insert Functions one by one into the B you have. In this case, there's a pattern so you could have built B with anonymous functions and comprehension:

M = 2
N = 2
x = 10

B = [ ((y) -> (y^a + b*y)) for a in 1:M, b in 1:N]

result1 = x .|> B  # result1[i] = B[i](x)

I'd rather not tie the array's indices to the functions though; you would have to keep making a new Function matrix for different M and N. Instead, you could make a more memory-efficient CartesianIndices matrix and use a function that takes in CartesianIndex:

# memory-efficient matrix of CartesianIndex{2}
indices = CartesianIndices((M,N))
# if x were an MxN Matrix, you could also do CartesianIndices(x)

f(y, a, b) = y^a + b*y
g(z, index::CartesianIndex{2}) = f(z, index[1], index[2])

result2 = g.(x, indices) # result2[i] = g(x, indices[i])

As an aside, it appears that in the anonymous function comprehension used to create my B, only 1 actual method is compiled, and each element is similar to an instance of a functor with a and b as fields:

struct P{A,B} <: Function # subtype Function to be similar to B
  a::A
  b::B
end

(p::P)(y) = y^(p.a) + (p.b)*x

PB = [P(a, b) for a in 1:M, b in 1:N]

result3 = x .|> PB # result3[i] = PB[i](x) = P(a, b)(x)

Upvotes: 1

Related Questions