User, @AndrzejKozlowski has uploaded a number of interesting demonstrations to the Wolfram Demonstration Project.

I have a particular interest these days in his Pricing a Bermudan Option with the Longstaff-Schwartz Monte Carlo Method and will likely submit a number of questions here as I try to understand what he does and the syntax he uses to do it.

In the notebook's Initialization Code section, the author has defined the following function:

step[stocks_?MatrixQ, {i_Integer, cashFlow_List}, k_, r_, times_] /; i >= 2 := 
      {pos = Position[stocks[[All, -i]], x_ /; x < k], 
       X, Y, 
       cashflow = cashFlow, 
       newcashflow, f, z},
    X = Extract[stocks[[All, -i]], pos]; 
    Y = 
      With[{csh = Extract[#, pos] &/@ cashflow}, 
        Plus @@ MapThread[Times, {discounts[Length[csh] + 1, r, times], csh}]]; 
    f[i][z_] = Fit[Transpose[{X, Y}], {1, z, z^2}, z]; 
    newcashflow = 
      If[f[i][#] > Max[k - #, 0], 0, Max[k - #, 0]] & /@ stocks[[All, -i]]; 
    cashflow = ((1 - Unitize[newcashflow])*#) &/@ cashflow; 
    {i + 1, cashflow = Prepend[cashflow, newcashflow]}]

I've included the entire function in case it helps clarify or improve the context of my question.

I want to understand the function's use of ?MatrixQ in the first argument and why the code would need it.

I just haven't come across this before now.

enter image description here

Does ?MatrixQ insure that stocks is a matrix? Any context or additional use cases of this syntax appreciated.


closed as off-topic by Daniel Lichtblau, m_goldberg, José Antonio Díaz Navas, Coolwater, LCarvalho Mar 12 '18 at 11:14

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Daniel Lichtblau, m_goldberg, José Antonio Díaz Navas, Coolwater, LCarvalho
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    $\begingroup$ Yes. Try f[mat_?MatrixQ]:=mat and evaluate f[1] or f[IdentityMatrix[3]]. $\endgroup$ – anderstood Feb 25 '18 at 16:33
  • 2
    $\begingroup$ Yes: just look at the "Applications" section of the Documentation Center page for MatrixQ. The more general use of _? is explained on the page ref/PatternTest (which I found by typing just ? into the search bar of the Documentation Center). $\endgroup$ – murray Feb 25 '18 at 16:38
  • 1
    $\begingroup$ Some possible uses: (1) It's a way to enforce one's own type-checking. (2) You can construct code like step[myStocks,..], in which step[] will not be evaluated until you've assigned a matrix to myStocks in the same way that Sin[x] is not evaluated until x has a numeric value, say, in Plot. $\endgroup$ – Michael E2 Feb 25 '18 at 17:10