0
$\begingroup$

I have the following matrix which represents an input from a .txt file. The first column gives the name of the random variable, the second the probability law, the third the parameters related to the law.

InputMatrix = {{"Phi", "Lognormal", {30, 2.4}}, {"C", 
"Lognormal", {5, 1}}}; 

in table form:

enter image description here

I built the following two functions :

LogNormalSolver[mat_] :=
  Module[{\[Lambda], \[Zeta]},
      NSolve[{mat[[1]] == Exp[\[Lambda] + \[Zeta]^2/2],
              mat[[2]] == Exp[\[Lambda] + \[Zeta]^2/2]*Sqrt[Exp[\[Zeta]^2] - 1],
      \[Lambda] \[Element] Reals, \[Zeta] > 0}, {\[Lambda], \[Zeta]}]
  ]

getLaw[mat_, i_] :=
  Module[{\[Mu]X, \[Sigma]X},
   Map[
    Which[# == "Lognormal",LogNormalDistribution[\[Mu]X, \ 
         [Sigma]X]/.LogNormalSolver[InputMatrix[[All, 3]][[i]]]] &, 
    mat[[All, 2]]][[i]]
 ]

My question is:

why can't the getLaw[] function access the two parameters calculated in the LogNormalSolver[] function and show me the following result ?

getLaw[InputMatrix, 1]

out:{LogNormalDistribution[\[Mu]X$15188, \[Sigma]X$15188]}

Note that I am a beginner in programming and I may not know all the subtleties with private and public variables etc...

Thank you in advance for the answer

$\endgroup$
1
  • $\begingroup$ Please describe what you want to do. It is hard to figure this out from your code alone. $\endgroup$ Jan 26, 2022 at 19:18

1 Answer 1

1
$\begingroup$

LogNormalSolver does not know about the local variables in getLaw. One solution would be to pass those variables to LogNormalSolver, so that it expresses its solution in terms of them

LogNormalSolver[mat_, lam_, zeta_] := 
  NSolve[{mat[[1]] == Exp[lam + zeta^2/2], 
    mat[[2]] == Exp[lam + zeta^2/2]*Sqrt[Exp[zeta^2] - 1], 
    lam \[Element] Reals, zeta > 0}, 
    {lam, zeta}
  ];

getLaw[mat_, i_] := 
  Module[{muX, sigX}, 
    Map[Which[# == "Lognormal", 
   LogNormalDistribution[muX, sigX] /. LogNormalSolver[InputMatrix[[All, 3]][[i]], muX, sigX]] &,
   mat[[All, 2]]][[i]]
];

getLaw[InputMatrix, 1]
(* {LogNormalDistribution[3.39801, 0.0798724]} *)
$\endgroup$
1
  • $\begingroup$ Helped a lot, thanks ! $\endgroup$ Jan 27, 2022 at 7:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.