Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System of equations using metaprogramming

I am trying to create a function that computes the residuals of a system of equations using metaprogramming.

This is what I have tried so far (toy example):

function syst!(x::Vector, ou::Vector)
    for i in 1:length(x)
        eval(parse("ou[$i] = x[$i]^2 + x[$i]"))
    end
    return ou
end

However, when I try to compute the function, Julia says that the variable x is not defined. But if I include a println(parse("ou[$i] = x[$i]^2 + x[$i]")) I get the code that would be "typed" in the body of the function (sorry if I'm not using the correct technical CS terms, I come from the "scientific culture").

Anyways, it seems that the parseed x lives in another scope. How can I bring that parsed x to the scope of the function so that it represents the x from the arguments of syst!?

Bonus: I have a system of 700 equations and they are amenable to be "typed" using metaprogramming, what's the best way/technique to create a function that computes the residuals of the system? Was I on the right track?

like image 265
amrods Avatar asked Mar 16 '26 05:03

amrods


1 Answers

Stefan's comment is right; in this specific example there is no need for metaprogramming. However, if you wanted to generate many lines similar to ou[i] = x[i]^2 + x[i] but different in complicated ways, you could generate them with a macro. See http://docs.julialang.org/en/release-0.4/manual/metaprogramming/. Macros expand to generated code "in place" as if you had typed it yourself, so variables can refer to the surrounding scope.

like image 195
Jeff Bezanson Avatar answered Mar 18 '26 03:03

Jeff Bezanson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!