How to create a function in Julia that has "varying constants"?

Viewed 86

Sorry, I know the question title is terrible, so let me exemplify. I am learning julia, and currently exploring matrix related codes. I am trying to calculate eigenvalue for a given matrix. SO I wrote this code:

using LinearAlgebra;
using Roots;

Δt(t) = det(t * I - Matrix{Int64}([4 2; 3 -1]));   # the matrix is hardCoded

# Calculate eigenvalues λᵢ
function calculateEigenValues()
  λ = find_zero(Δt, (1, 100))    
  println(λ)  # output = 5
end

So in this case, the matrix is hard-coded inside the characteristic equation, Δt. I wish to pass some matrix A as a parameter instead of hard-coding it, and so I wrote this:

using LinearAlgebra;
using Roots;
using Polynomials;

Δt1(t, A::Matrix{Int64}) = det(t * I - A) # Matrix{Int64}([4 2; 3 -1]));


function calculateEigenValuesV1()
  #dt = Δt(1, A)
  x = variable()  # from package Polynomials 
  A = Matrix{Int64}([4 2; 3 -1]);
  λ = find_zero(Δt1(x, A), (1, 100));  # crashes! no idea how to pass a value, and keep the other one as a variable
  println(λ)
end

And it does not work. I guess I am passing a variable, and a matrix in Δt1, and the output is a function. that function is set as the first parameter of find_zero(). How to write this correctly in julia?

[In case you're wondering, I've just learnt to use the builtin library, and that is not the problem. Sample code:

  A = Matrix{Int64}([4 2; 3 -1]);
  eigenValAndVec = eigen(A);

  A = Matrix{Int64}([4 2; 3 -1]);
  foo = eigen(A);
  foo.values; foo.vectors;  # <-- ok

I'm just curious about my error explained above. ]

1 Answers

Just to recap the ideas from the comments (and possibly close this question). The following code is a more idiomatic Julia version of the OP code to find an eigenvalue (without using eigen from LinearAlgebra package):

using LinearAlgebra
using Roots

Δt1(t, A) = det(t * I - A)

function calculateEigenValuesV1(A)
    λ = find_zero(x->Δt1(x, A), (1, 100))
    return λ
end

After definining these functions, an example could go as:

julia> A = [4 2; 3 -1]
2×2 Matrix{Int64}:
 4   2
 3  -1

julia> calculateEigenValuesV1(A)
5.0
Related