Tag Info

Hot answers tagged

77

I'll just throw in a few random thoughts in no particular order, but this will be a rather high-level view on things. This is necessarily a subjective exposition, so treat it as such. Typical use cases In my opinion, Compile as an efficiency-boosting device is effective in two kinds of situations (and their mixes): The problem is solved most efficiently ...


53

The main change since that time seems to be that the modern way of using options is associated with OptionsPattern[] - OptionValue commands. A typical way of defining a function would be: Options[f] = { FirstOption -> 1, SecondOption ->2 } f[x_,y_,opts:OptionsPattern[]]:= Print[{x,y,OptionValue[FirstOption],OptionValue[SecondOption]}] ...


27

Here is a practical example from a StackOverflow question. I hope that it gives a good overview of the basic methods. Question What would be the best way to make a function out of the below code ? It would take a dataList as well as some graphical options (such as colors) as arguments and return a customized tabular representation as shown ...


19

Part of what you are asking is of course a matter of taste and habits, but here are my 2 cents: 1) if you want Mathematica to find your package files with a Needs or Get their context names must agree with the hierarchy of directories and filenames. I don't see any good reasons to diverge from that standard convention. For complex packages with many files ...


19

All palette state (i.e., variables which affect the palette and should be remembered between sessions) should be vectored through the palette's TaggingRules option, and its initialization should be done in the palette's NotebookDynamicExpression option. That, plus context isolation of any kernel functions you need to define should solve all of the points ...


18

Setting SetSystemOptions[ "CompileOptions" -> "CompileReportExternal"->True] will emit a message when parts of your function do not get compiled. After compilation, Needs["CompiledFunctionTools`"] followed by CompilePrint[cF] (with cF the function you have compiled will display some bytecode; looking for CopyTensor or MainEvaluate in that helps locate ...


14

While @Albert gave an excellent answer, here are my two cents: Naming One thing which is true almost always: make your context name for the package the same as the file name for that package (without .m, of course). While you technically can use a different name, this will make your life harder. A lot depends on the complexity of the project. If it fits ...


13

You can use String "keys" for indexed variables, as I did for A combination of Set::setraw and Set::shape errors. The strings can have spaces or any other characters you want to use: var["Degree of the First Polynomial"] = (* stuff *); You also have a wide range of characters, many of which can be used in Symbol names. Go to menu Palettes > Special ...


13

There are a number of options and their attractiveness will depend on the scenario for their use, therefore it is difficult to make any broad recommendations of best practice. I will say that generally it is not recommended to rely on global assignments as in your first example, because this method scales poorly and because it is easy to make mistakes and ...


12

This is not a question of functional style per se. Functional style is, AFAICT, largely about avoiding mutable state (where possible), using functions as fundamental building blocks, using certain abstractions such as higher-order functions, closures, function composition, etc., and avoiding mixing state and behavior. I think that the value of pre ...


12

I have answered almost exactly this question (somewhat more general one, if we interpret this one as being concerned only with Throw and Catch) here. Since you asked a more narrow one, I feel it may be appropriate to borrow a part of my answer, to have it here. The method This method is IMO almost never appropriate for the top-level functions that are ...


11

If you want to revert the entire system to some state, then CleanSlate` may be the best option. If you want to unload a few specific packages though, you can use my package PackageManipulations`, available here. It has a function PackageRemove, which does exactly that. It has an accompanying notebook with explanations. Some additional notes on it are in this ...


11

This question was indeed discussed on SO, here. I am usually using the version of CleanUp function by WReach, from that answer. It is however not fully bulletproof, as I noted in comments to that answer. Particular pieces of code which are problematic are nested exceptions or aborts like these: Throw[Unevaluated[Abort[]]] or ...


10

Providing optional arguments to functions is rather straight forward. I'll show you three possibilities. Positional arguments This defines a function with a second optional argument. If the argument is omitted it is taken to have the default value. fx[list_, panel_: True] := fx0[list, panel] Named arguments This sets up a default value for a named ...


10

For additional reference, found within the file $InstallationDirectory/SystemFiles/Kernel/TextResources/English/Messages.m are all of the defined messages for the system, and there are 11 General messages for Options that do not conform. The list is General::optlist = "Value of option `1` -> `2` should be a list." General::optb = "Optional object `1` in ...


10

In V10, another option is to use Association. par=<|"mu"->1,"sigma"->1,"lb"->0,"ub"->10|>; f[x_, p_Association:par] := PDF[LogNormalDistribution[p["mu"], p["sigma"]], x] Plot[f[x, ##], {x, #lb, #ub}] &@par Another form for Plot is: Plot[f[x, par], {x, par@"lb", par@"ub"}] And as @Mr.Wizard commented, you can use the default ...


9

I would use the Execute Around Block pattern, which is superficially similar to RAII in c++. A simple example is what I use for ensuring that streams are closed after execution: OpenAndRead[file_String, fcn_]:= Module[{strm, res}, strm = OpenRead[file]; res = CheckAbort[ fcn[strm], $Aborted ]; Close[strm]; If[res === $Aborted, Abort[], res] ...


9

Yes, plain-text programming, as you call it, can be done in Mathematica. It is often used for developing packages (.m files). Try searching this site with the phrase "package development" to get more info. There is even a built-in working environment supporting package development. It has its own style sheet in which code-form cells (plain-text ...


6

It comes down to the DRY principle: The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." The content management system Wordpress doesn't use object oriented paradigms and so for that reason it looks exactly like your code. Tens of thousands of lines of code like this. ...


6

There is an undocumented function, CheckAll, that can be used for this purpose. It dates back to at least version 7. All the usual caveats about undocumented functions apply -- it might not be supported in future releases, there may be gaps in its functionality, etc. Buyer beware. The usage information looks like this: The usage text is slightly in ...


6

Not a complete answer by any means but if you are new to Compile I highly recommend that you read the tutorial on the Mathematica compiler. It is very useful.


6

This answer I gave illustrates how to define the type of local variables used in a Module inside Compile which helps solve some types of issues as compiled functions sometimes are more strongly typed than non compiled ones. Internal`Bag inside Compile Inlining external functions inside Compile can sometimes be problematic (because of the need of definining ...


5

The cleanest possible kernel you can get is starting a kernel only (no front end) with the -noinit option. math -noinit The front end will evaluate a lot of code when it connects to the kernel. -noinit prevents the kernel from loading initialization files (init.m). I don't believe you can get to a purer state than this unless you start surgically ...


5

There are several things that I think you misunderstand. The most important recommendation would be to use this question as a trigger to go to the help and read up on the functions involved and on related tutorials First, a working solution to ease your mind fx1[x_] := 1 + x + RandomVariate[NormalDistribution[]]; fx2[x_] := x^2; fx3[x_] := x - 2; ...


4

Backtracking is never efficient so I would suggest always using C for this. However if you must do this in mathematica, here is an example of the generalized backtrack algorithm (as taken almost literally from the Combinatorica` package's Backtrack function) specifically applied to graph coloring: backtrack[space_List, partialQ_, solutionQ_, flag_: 1] := ...


4

You could generate the palette from code in a separate notebook, and have the generated palette use a unique context by setting CellContext -> Notebook when creating the palette notebook. I think this should help with items 2, 3, and 5. Example (there may be better ways..) CreateDocument[ {Cell[BoxData[MakeBoxes[x = 2]], "Input"]}, CellContext ...


4

I mentioned this in a comment, but I believe this might really be the correct answer to your specific inquiry about underscore. You can escape underscore (Esc+_+Esc or Ecs+ls+Esc), which will give you a \[LetterSpace], which looks like underscore but is slightly lighter. This is just treated like a regular old letter and you can therefore use it in variable ...


4

This question is related to What are the advantages of using .nb rather than .m files? That question details some of the differences you will face in using a plaintext format. If you are merely seeking manual code formatting rather than having Mathematica reflow your input you can use the Code cell style, or a customized version (e.g. without being ...


4

I like to save my files in "plaintext" for 3 reasons: Can use SVN to have embedded version information, look at diffs from coauthors, etc. Don't mix the code itself with the output of the code, which also makes interacting with coauthors difficult and is unclear what has been run and what hasn't. Be able to run the files commandline on a cluster if ...


4

I find using Module the easiest way to keep track of things when it comes to these kinds of situations. plot[x_, s_] := Module[{b, w, c, ua, ub}, b = 10 x; w = s + b; c = x^2; ua = w - c; ub = w - c^2; Plot[{ua, ub}, {x, -5, 5}]] plot[randomVar, 5]



Only top voted, non community-wiki answers of a minimum length are eligible