1
$\begingroup$

The code below generates some data and defines a function f[x,cb]:=NMaximize[expr,x] that upon being evaluated returns: {function value at max $x$,the function maximizing $x$}.

Nobs = 100;
wi = RandomVariate[BetaDistribution[2, 2], Nobs];
c = 0.1;
\[Lambda]i = RandomVariate[BetaDistribution[2, 4], Nobs];
f[pbar_, cb_] := 
  NMaximize[
   Sum[((((1 - \[Lambda]i[[i]])*Min[wi[[i]], pbar] + \[Lambda]i[[i]]*
             c) - c)*
        Boole[wi[[
            i]] - ((1 - \[Lambda]i[[i]])*
              Min[wi[[i]], pbar] + \[Lambda]i[[i]]*c) - cb >= 
          Max[wi[[i]], 0]] + (pbar - c)*
        Boole[wi[[i]] - pbar >= 
          Max[wi[[i]] - ((1 - \[Lambda]i[[i]])*
               Min[wi[[i]], pbar] + \[Lambda]i[[i]]*c) - cb, 0]]), {i,
       1, Nobs}]*(1/Nobs), pbar ];

Evaluating the functions yields:

In[197]:= f[x, .1]
Out[197]= {0.146006, {x -> 0.30858}}

I want two plots:

  1. plot f[x,cb][[1]] in the {X,Y} space where X = cb / (Y - c)
  2. plot f[x,cb][[2]] in the {X,Y} space where X = cb / (Y - c)

Any suggestions on how I can do this? Since the function is not continuous I have tried working with DiscretePlot[], but I am having a hard time getting the plotting to work.

PS: the function is rather slow to evaluate--so any comments on how to write the function more efficiently are also appreciated.

$\endgroup$
3
$\begingroup$

I'm not sure I understand what you are doing but the plots plat should be simple. We put all your results in a Table using ParallelTable to use all available cores in your CPU.

data = ParallelTable[
   Block[
    {r = f[x, cb], fmax, xmax},
    fmax = First[r];
    xmax = (x /. Last[r]);
    {cb, xmax, fmax}
    ], {cb, 0, 0.3, 0.3/20}];

TableForm[N@data,  TableHeadings -> {Range[Length[data]], {"cb", "xmax", "fmax"}}]

Mathematica graphics

ListLinePlot[
 data[[All, {1, 3}]]
 , PlotRange -> {0, 0.2}
 , InterpolationOrder -> 3
 , PlotLabel -> "fmax vs cb"
 , Frame -> True]

Mathematica graphics

ListLinePlot[
 data[[All, {1, 2}]]
 , PlotRange -> {-1/2, 2}
 , InterpolationOrder -> 2
 , PlotLabel -> "xmax vs cb"
 , Frame -> True]

Mathematica graphics

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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