# Macros and Globals

Macros and globals allow you to define custom model code that is included in the model.

For instance, you could use macros to define a custom function that is accessible in all the equations in your model. For example, imagine you had a model where you needed to calculate the sine of the division of the sum and product of three numbers in many different places. Now you could write this equation out wherever it occurred. However, that might be tedious and prone to error. Additionally, if you later decided you had to use the cosine instead of sine, there would be many different parts of your model you would need to update.

By defining macros for models we can create a function to carry out this repetitive task. Insight Maker can define single-line functions like so:

myFn(a, b, c) <- sin((a+b+c)/(a*b*c))

Multiline function can be defined using this syntax:

Function myFn(a, b, c)
x <- (a+b+c)
y <- (a*b*c)
return sin(x/y)
End Function

Macros can also be used to define variables that will be available in the model such as a counter. Another use of macros is to set the random seed for the model, so the same set of random numbers will be generated each model run:

setRandSeed(99)

As another example, if you wanted a matrix multiplication function (useful as the * operator does element-wise multiplication in Insight Maker), you could use something like this:

function MatMult(a, b)
# assumes a and b are matrices defined as a vector of rows
# assumes matrices are correctly sized, does not do any error checking
res <- repeat(repeat(0,a.length()), b{1}.length())
for row from 1 to a.length()
for col from 1 to b{1}.length()
total <- 0
for item from 1 to a{1}.length()
total <- total + a{row, item} * b{item, col}
end loop
res{row, col} <- total
end loop
end loop
return res
end function

Once placed in your Macros, you can call this function anywhere in your model formulas. For example:

MatMult({{1,2,3}, {4,5,6}}, {{7,8},{9,10},{11,12}})