Implementing an awfull long function in MATLAB

37 Views Asked by At

I have a function

$$ f(\tau, X_1, X_2, V_1, V_2) = \ e^{A(\tau) + z_1 X_1 + z_2 X_2 + B_1(\tau)V_1 + B_2(\tau)V_2+ B_m(\tau)V_m} $$ That I want to implement and do some numerics on in MATLAB. The thing is that its awfully long when inserting $A(\tau), B_1 (\tau), B_2 (\tau)$ and $B_m(\tau)$. E.g.

$$ B_m(\tau) = - \frac{z_1 \sigma_{1m} \sigma_{m} \rho_{1m} + z_2 \sigma_{2m} \sigma_{m} \rho_{2m} - \kappa_m}{\sigma_m^2} + \\ \sqrt{\frac{\sigma_{1m}^2(z_1^2 - z_1) + \sigma_{2m}^2(z_2^2 - z_2) + \sigma_{1m} \sigma_{2m} \rho_{12m} z_1 z_2}{\sigma_m^2} - \left( \frac{z_1 \sigma_{1m} \sigma_{m}\rho_{1m} + z_2 \sigma_{2m} \sigma_{m} \rho_{2m} - \kappa_m}{\sigma_m^2} \right)^2} \\ \cdot \\ \tan \Bigg( \sqrt{\sigma_m^2( \sigma_{1m}^2(z_1^2- z_1) + \sigma_{2m}^2 (z_2^2 - z_2) + \sigma_{1m} \sigma_{2m} \rho_{12m} z_1z_2 ) - (z_1 \sigma_{1m} \sigma_m \rho_{1m} + z_2 \sigma_{2m} \sigma_m \rho_{2m} - \kappa_m)^2} \\ \left( \frac{\tau + C_m}{2} \right)\Bigg) \\ with \\ C_m = \frac{2 \arctan \left(\frac{z_1 \sigma_{1m} \sigma_{m} \rho_{1m} + z_2 \sigma_{2m} \sigma_{m} \rho_{2m} - \kappa_m}{\sigma_m^2} \right) }{\sqrt{\sigma_m^2( \sigma_{1m}^2(z_1^2- z_1) + \sigma_{2m}^2 (z_2^2 - z_2) + \sigma_{1m} \sigma_{2m} \rho_{12m} z_1z_2 ) - (z_1 \sigma_{1m} \sigma_m \rho_{1m} + z_2 \sigma_{2m} \sigma_m \rho_{2m} - \kappa_m)^2}} $$

So implementing this by just typing everything in will with high probability result in multiple small errors, taking week to find.

In best of worlds I would do something like

A = @(t) ...

B_1 = @(t) ...

B_2 = @(t) ...

and then

f = @(...) exp( A + z_1X_1 + z_2X_2 + B_1V_1 ...)

But to my knowledge this is not possible. Thus I'm looking for helpful advice on how to implement such a function, reducing the probability of human error as much as possible.

Useful information Actually for the task Im about to do, I will wary $z_i$ and the rest will be known. So basically it boils down to $$ f(z_1,z_2) = e^{A(z_1,z_2) + z_1X_1 + z_2X_2 + B_1(z_1, z_2)V_1 + B_2(z_1, z_2)V_2 + B_m(z_1, z_2)V_m} $$

1

There are 1 best solutions below

1
On BEST ANSWER

You can make multiple inline functions, and use other functions inside an inline function definition, like so:

f1=@(x)(x^2+1);
f2=@(x)(x+5);
g=@(x)(f1(f2(x)));
g(5)

ans =
   101