0
$\begingroup$

I'm sure this has been asked, but I can't seem to find the correct terms to find it.

I have a function that looks something like this

myFunction[data_]:=Module[{result, x, y}, 
      result = NMinimize[ myModel[data, x, y], {x, y}];
      Return[result]
]

When I use it my results look something like

{1234, x$2319->10, y$2319 -> 0.023}

Besides working with global variables, how do I remove the $2319 from x$2319 and y$2319 (ideally as part of myFunction) so I can use the results more easily?

$\endgroup$
  • $\begingroup$ Don't localize x and y with the $Module? $\endgroup$ – b3m2a1 Sep 7 '17 at 5:11
  • $\begingroup$ @b3m2a1 Note the phrase "Besides working with global funcdtions..." (which should read "Besides working with global variables") $\endgroup$ – mikemtnbikes Sep 7 '17 at 5:19
  • $\begingroup$ This is what contexts are built for. One can strip the numbers via SymbolName and ToExpression, but that's hacky and not likely to be a solid solution long term. $\endgroup$ – b3m2a1 Sep 7 '17 at 5:25
  • $\begingroup$ Not the same problem but related by solution: 114769 $\endgroup$ – Kuba Sep 7 '17 at 5:30
1
$\begingroup$

Best way to handle this is to pass in symbols from caller that you want to be part of returned expression.

myFunction[data_,x_,y_]:=Module[{result},
result={data,x,y}
];

ClearAll[x,y]
myFunction[{1,2,3},x,y]

Mathematica graphics

No dollars any more. This is how Mathematica does it. For example, NDSolve and DSolve etc... they take in y[x] and also x from user scope so that the result returned will not have $$ in it.

See module-and-local-variable also

$\endgroup$
0
$\begingroup$

The solution I like best is to replace Module[] with Block[]. Simple and given in Module and Local variable as pointed out by Nasser (thanks!).

$\endgroup$
  • 2
    $\begingroup$ Check what happens if x and y have global values before you call this function. Wanting to localize and wanting to return x and y from the function are kind of contradictory. $\endgroup$ – Szabolcs Sep 7 '17 at 7:41

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