see ?ListConvolve
LaplaceTransform[x,x,t]; ClearAttributes[LaplaceTransform,ReadProtected] ??LaplaceTransform
But better to use this:
Needs["GeneralUtilities`"]; PrintDefinitions@Charting`FindTicks
Thanks to https://mathematica.stackexchange.com/questions/132568/extract-ticks-from-plot
The above works if the function is not read protected.
See also this link
from the net. Using Times font family is the idea.
data = Table[{x, Random[Real, {0, x}]}, {x, 0, 10}]; ListPlot[data, Frame -> True, PlotStyle -> {FontFamily -> "Times"}, PlotLabel -> "64Cycles in FIFO", FrameLabel -> {"S/N dB", "RMS error mm"}]
|
|
I made this simple diagram to help me understand pure functions.
I made this diagram to show the installation tree structure.
?Apart
To insert |
|
To enter \(\pi \) |
|
To enter E |
|
|
|
|
|
Trace[Integrate[x, {x, 1, 2}], TraceInternal -> True]
ParametricPlot[{Sin[u], Cos[u]}, {u, 0, 2 Pi}, AspectRatio -> 1]
Suppose we are given \(z=x e^{-y}, x=\cosh (t), y=\cos (s)\) and need to find \(\frac {dz}{ds}\)
x[t_] := Cosh[t] y[s_] := Cos[s] z[x_, y_] := x[t] Exp[-y[s]] D[z[x, y], s]
|
(Cosh[t]*Sin[s])/E^Cos[s]
|
Another example: \(u=x^2 y^3 z, x=\sin (s+t), y=\cos (s+t), z=e^{s t}\) and we need to find \(\frac {du}{ds}\) and \(\frac {du}{dt}\)
rootsPlot[poly_, z_] := ListPlot[{Re[z], Im[z]} /. NSolve[poly == 0, z], PlotStyle -> Directive[PointSize[0.015]]]; rootsPlot[z^7 - 1, z]
|
|
For example, to integrate this below, for n positive integer we do
Integrate[Sin[n x]^2, {x, 0, Pi}]
|
|
Assuming[Element[n, Integers] && n > 0, Integrate[Sin[n x]^2, {x, 0, Pi}]]
|
|
eq = f == x^3 + 6/x^3; Reduce[{eq, x^3 == z}]
|
(x == z^(1/3) || x == (-(-1)^(1/3))*z^(1/3) || x == (-1)^(2/3)*z^(1/3)) && z != 0 && f == (6 + z^2)/z
|
f[z_] := z^2 ParametricPlot[Through[{Re, Im}[f[x + I y]]], {x, -2, 2}, {y, -1, 1}, PlotStyle -> Red]
|
|
In[60]:= s = HoldForm[1 + 2] Out[60]= HoldForm[1 + 2] In[61]:= ReleaseHold[s] Out[61]= 3
One way is to use Show
By Bill Rowe http://forums.wolfram.com/mathgroup/archive/2004/Apr/msg00357.html
In[1]:= Timing[For[sum = 0; n = 1, n < 100001, n++, sum += n]] Out[1]= {1.2999999999999998*Second, Null} In[2]:= Timing[Plus @@ Range[10000]] Out[2]= {0.009999999999999787*Second, 50005000}
Use notation package
See using_zero_index_in_Mathematica
In[62]:= eq = x^2 + Sin[4*a] == 3 - Derivative[1][y][t] Out[62]= x^2 + Sin[4*a] == 3 - Derivative[1][y][t] In[63]:= lhs = eq /. (lhs_) == (rhs_) -> lhs Out[63]= x^2 + Sin[4*a] In[64]:= rhs = eq /. (lhs_) == (rhs_) -> rhs Out[64]= 3 - Derivative[1][y][t]
Rememebr: Position
and Cases
return result that can be used by Extract
directly. But
can’t be used by Part
directly.
a = Table[RandomInteger[100], {4}, {4}]
|
Out[69]= {{55, 63, 78, 45}, {13, 45, 67, 1}, {94, 32, 48, 90}, {31, 75, 43, 60}}
|
a[[All,1]]
|
Out[70]= {55, 13, 94, 31}
|
Find rows which has elements in first column less than 3 in the following
a = {{1, 2, 3}, {4, 5, 8}, {7, 8, 9}}
Reference: how-to-extract-rows-from-matrix-based-on-value-in-first-entry
The solution using pattern below (by WRech) is interesting since the same pattern can be
used by Cases
and Position
.
solution by me
pos = Position[a[[All,1]], _?(#1 <= 4 & )] Out[73]= {{1}, {2}} Extract[a, pos] Out[74]= {{1, 2, 3}, {4, 5, 8}}
by Simon
pos = Position[a, _List?(First[#1] <= 4 & ), {1}] Out[75]= {{1}, {2}} Extract[a, pos] Out[76]= {{1, 2, 3}, {4, 5, 8}}
By Asim
Pick[a, a[[All,1]], _?(#1 <= 4 & )] Out[77]= {{1, 2, 3}, {4, 5, 8}}
By WReach
Cases[a,{n_,__}/;n<=4,{}] Out[78]= {{1,2,3},{4,5,8}}
By WReach
pos=Position[a,{n_,__}/;n<=4,{}] Extract[a,pos] Out[79]= {{1},{2}} Out[80]= {{1,2,3},{4,5,8}}
Random values on the diagonal
DiagonalMatrix[Table[Random[], {3}]]
Ones on the diagonal
DiagonalMatrix[Table[1, {3}]]
one way, using SparseArray
Normal[SparseArray[{{i_, i_} :> 2*i, {i_, j_} :> i + j /; i < j}, {5, 5}]] Out[81]= {{2, 3, 4, 5, 6}, {0, 4, 5, 6, 7}, {0, 0, 6, 7, 8}, {0, 0, 0, 8, 9}, {0, 0, 0, 0, 10}}
Or using Table. But notice that in SparseArray, the ’zeros’ are already the default case, so using SparseArray is simpler.
Table[If[i == j, 2*i, If[i < j, i + j, 0]], {i, 5}, {j, 5}] Out[82]= ... same as above
see ?Tr[a]
a = {{1, 2, 3}, {4, 5, 8}, {7, 8, 9}} Tr[a, Times] Out[84]= 45
by Jon MacLoone
DiagonalQ[m_List] /; ArrayDepth[m] === 2 && Equal @@ Dimensions[m] := And @@ Flatten[MapIndexed[#1 === 0 || Equal @@ #2 & , m, {2}]]; DiagonalQ[m_] := Return[False]; a = {{1, 2}, {2, 4}} b = {{1, 0}, {0, 2}} DiagonalQ[a] Out[89]= False DiagonalQ[b] Out[90]= True
By Paul Abbott
Clear[DiagonalQ]; DiagonalQ[(m_)?MatrixQ] /; SameQ @@ Dimensions[m] := m === DiagonalMatrix[Tr[m, List]] DiagonalQ[a] Out[93]= False DiagonalQ[b] Out[94]= True
Find location of zeros in this matrix
a = {{1, 2, 3}, {4, 0, 8}, {7, 8, 0}}
one way
Position[a, 0] Out[96]= {{2, 2}, {3, 3}}
Another way
Position[a, _?(#1 == 0 & )] Out[97]= {{2, 2}, {3, 3}}
find all elements between 4 and 8
a = {{1, 2, 3}, {4, 0, 8}, {7, 8, 0}} Position[a, _?(#1 >= 4 && #1 <= 8 & )] Out[99]= {{2, 1}, {2, 3}, {3, 1}, {3, 2}} Extract[a, %] Out[100]= {4, 8, 7, 8}
Using Part
to inser 99 in position (1,1)
a = {{1, 2, 3}, {4, 0, 8}, {7, 8, 0}} a[[1,1]] = 99; a Out[103]= {{99, 2, 3}, {4, 0, 8}, {7, 8, 0}}
a = {{1, 2, 3}, {4, 0, 8}, {7, 8, 0}}
To insert this row in the second row in matrix above
row = {97, 98, 99}; newa = Insert[a, row, {2}] Out[106]= {{1, 2, 3}, {97, 98, 99}, {4, 0, 8}, {7, 8, 0}}
or just use ’2’, it will also work
newa = Insert[a, row, 2] Out[107]= {{1, 2, 3}, {97, 98, 99}, {4, 0, 8}, {7, 8, 0}}
a = {{1, 2, 3}, {4, 0, 8}, {7, 8, 0}}
To insert this column in the second column position in above matrix
column = {97, 98, 99};
one way
newa = Transpose[Insert[Transpose[a], column, 2]] Out[110]= {{1, 97, 2, 3}, {4, 98, 0, 8}, {7, 99, 8, 0}}
another way
Normal[SparseArray[{{i_, j_} :> column[[i]] /; j == 2, {i_, j_} :> a[[i,j]] /; j == 1, {i_, j_} :> a[[i,j - 1]] /; j > 1}, {3, 4}]] Out[111]= {{1, 97, 2, 3}, {4, 98, 0, 8}, {7, 99, 8, 0}}
Another way by Leonid Shifrin how-to-insert-a-column-into-a-matrix-the-correct-mathematica-way
MapThread[Insert, {a, column, Table[2, {Length[column]}]}] Out[112]= {{1, 97, 2, 3}, {4, 98, 0, 8}, {7, 99, 8, 0}}
Another by Leonid Shifrin
ArrayFlatten[{{a[[All,1 ;; 1]], Transpose[{column}], a[[All,2 ;; All]]}}] Out[113]= {{1, 97, 2, 3}, {4, 98, 0, 8}, {7, 99, 8, 0}}
Given
a = {{1, 2, 3}, {4, 0, 8}, {7, 8, 0}}
and we want to make matrix { {a,a},{a,a} }
b = ArrayFlatten[ {{a, a}, {a, a}}] Out[118] {{1, 2, 3, 1, 2, 3}, {4, 0, 8, 4, 0, 8}, {7, 8, 0, 7, 8, 0}, {1, 2, 3, 1, 2, 3}, {4, 0, 8, 4, 0, 8}, {7, 8, 0, 7, 8, 0}}]
Given
a = {{1, 2, 3}, {4, 0, 8}, {7, 8, 0}}
and we want to apply the this function to it
f[x_] := x + 2*Sin[x]
Then using Map
r = Map[f[#1] & , a, {2}] Out[123]= {{1 + 2*Sin[1], 2 + 2*Sin[2], 3 + 2*Sin[3]}, {4 + 2*Sin[4], 0, 8 + 2*Sin[8]}, {7 + 2*Sin[7], 8 + 2*Sin[8], 0}}
Remove["Global`*"] Refine[Sin[x]^2 + Cos[x]^2 == q, q == 1] Out[125]= True
One way
$PrePrint = If[MatrixQ[#], MatrixForm[#], #] &; m = {{1, 2}, {3, 4}}
Another otpion is to use TraditionalForm
. Can change default form from the menu, so this
way no need to change $PrePrint
Use Boxed -> False
Plot3D[2 x + 7 y, {x, -4, 4}, {y, -4, 4}, Boxed -> False, AxesEdge -> {{-1, -1}, {-1, -1}, {-1, -1}}, AxesLabel -> {x, y, z}]
|
|
One way to use Transpose
x = Table[i, {i, 0, 2 Pi, Pi/10}]; y = Sin[x]; data = Transpose[{x, y}]; ListPlot[data, Joined -> True]
|
|
v = {1, 2, 3}; ListCorrelate[v, v, {-1, 1}, 0] Out[139]= {3, 8, 14, 8, 3}
In Matlab it is
v=[1,2,3] xcorr(v,v) ans = 3 8 14 8 3
From the net, lost reference
See also how-to-draw-a-spring
maxy = Pi; Row[{VerticalSlider[Dynamic[maxy], {-2 Pi, 2 Pi}, Appearance -> "LeftArrow"], Dynamic@Plot[Sin[x], {x, -Pi, Pi}, PlotRange -> {{-Pi, Pi}, {-maxy, maxy}}, ImageSize -> 200]}]
|
|
some notes below
Precision means the variability between estimates Accuracy means the amount of deviation between the estimate and the "true value"
The condition number is the ratio of the output error to the input error. if the condition number is about 10k, then one loses about k digits of accuracy.
The main sources of inaccuracy (= error) is truncation error and round-off error.
From the above dart diagram, then we can say this: a value is accurate if it is near the bull-eye. But if is away from the bull-eye, but it is always away from the bull-eye and in the same place, then it is precise. So something can be precise but not accurate. So precise has to do with repeated values. i.e. one can’t say a value is precise, but must talk about an experiment being precise, it is produced same result each time (or very close results each time).
So, it is best of course to be both accurate and precise. So what does it mean to be accurate but not precise? using the above dart diagram, it means values generated from the experiment are always close to the pull eye, but not in the same locations.
From http://forums.wolfram.com/mathgroup/archive/2010/Jan/msg00917.html
The definition of precision in Mathematica is this. Suppose x is a number known up to an error of epsilon, that is it can be viewed as lying in the interval (x-epsilon/2,x+epsilon/2). Then its precision is -Log[10,epsilon/x]. Its accuracy is -Log[10,epsilon]. The two are related by the equation: Precision[x] - Accuracy[x] == RealExponent[x] The interpretation in terms of digits is only approximate. Both accuracy and precision can be negative - this depends on the scale of the number i.e. RealExponent. A number will have negative accuracy if its absolute error is large. It is easy to produce such numbers by cancellation With[{x = N[10^100, 50] - N[10^100, 50]}, Accuracy[x]] -50.301 On the other hand, since $MinPrecision 0 You won't normally in Mathematica see numbers with negative Precision. Precision is the main concept, Accuracy is only used because Precision is singular at 0 (remember - its relative error). It's all perfectly documented so this tired scape goat is not available this time.
By Bob Hanlon from math group:
Clear[x, $PrePrint] expr = {E^x, x, x^2, Log[x]}; Position[expr, _?( !PolynomialQ[#1, x] & ), 1] Out[146]= {{1}, {4}}
Use SphericalRegion->True
ListPlot3D[Table[RandomReal[], {5}, {5}], AxesLabel -> {"x", "y", "z"}, ImageSize -> {200, 200}, ImagePadding -> 20, SphericalRegion -> True];
This question was posted on the net. Given
b:=Table[{x,y},{x,1,6},{y,1,6}]
select from it elements \(x,y\) which satsify \(x+y>9\)
some answers
(me) Select[Flatten[b, 1], #1[[1]] + #1[[2]] > 9 & ] Out[152]= {{4, 6}, {5, 5}, {5, 6}, {6, 4}, {6, 5}, {6, 6}}
Adriano Pascoletti answer
Cases[b, {x_Integer, y_Integer} /; x + y > 9, {2}]
Bill Row answer
Cases[Flatten[b, 1], _?(Total[#1] > 9 & )]
Murray Eisenberg answer
Select[Flatten[b, 1], First[#1] + Last[#1] > 9 & ]
Given a matrix, say which has Indeterminate and we want to change all these entries in the matrix by zero.
mat = {{-1., -1., Indeterminate, -1., -1.}, {-1., -1., Indeterminate, -1., -1.}, {Indeterminate, Indeterminate, Indeterminate, Indeterminate, Indeterminate}, {-1., -1., Indeterminate, -1., -1.}, {-1., -1., Indeterminate, -1., -1.}} p = Position[mat, Indeterminate] mat = ReplacePart[mat, p -> 0] Out[169]= {{-1., -1., 0, -1., -1.}, {-1., -1., 0, -1., -1.}, {0, 0, 0, 0, 0}, {-1., -1., 0, -1., -1.}, {-1., -1., 0, -1., -1.}}
another example, given a matrix of values, replace those values which are less than \(0.5\) by
NULL
n = 5; a = Table[RandomReal[], {n}, {n}]; p = Position[a, x_ /; x < 0.5]; a = ReplacePart[a, p -> Null] Out[173]= {{Null, Null, Null, 0.6781657418995635, 0.7290662037036753}, {Null, 0.7084980071179792, Null, Null, 0.5811489862295911}, {Null, Null, 0.8467863882617719, Null, 0.8891915946646993}, {0.8173279058333203, 0.7272894246356278, Null, Null, 0.8665880423275274}, {Null, Null, 0.662026816962838, 0.5982839657423036, 0.6603967280952212}}
see full-documentation-for-appearanceelements
list = { "AutorunPlayButton", "BookmarksButton", "BookmarksPlayButton" "ContentResizeArea", "DirectionButton", "FasterSlowerButtons", "HideControlsButton", "InteractiveTradingChartMenu", "InteractiveTradingChartSnapshotButton", "InteractiveTradingChartResetButton", "InputField", "InlineInputField", "ManipulatePlayButton", "ManipulateMenu", "PlayPauseButton", "ProgressSlider", "ResetButton", "SnapshotButton", "StepLeftButton", "StepRightButton", "UpdateButton", None};
one way
p = Plot[Sin[x], {x, 0, Pi}, MaxRecursion -> 0, PlotPoints -> 10]; data = Cases[Normal[p], x_Line :> First[x], Infinity]; Show[p, ListPlot[data, PlotStyle -> Red]]
|
|
p = ContourPlot3D[x^2 + y^3 - z^3 == 0, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}, PlotPoints -> Automatic] data = (InputForm@p)[[1, 1, 1]]
and
data = Reap[DensityPlot[Sin[x*y], {x, 0, 2 Pi}, {y, 0, 2 Pi}, EvaluationMonitor :> Sow[{x, y, Sin[x*y]}]]][[2, 1]]; ListPlot3D[data]
There is no build-in struct or record in Mathematica. But this is what I do. Since in M a matrix can include non-numeric data, I use a list for a record, and then use a matrix to make an array of records (or array of structs). I just need to make a constant to indicate the field name in the record, to make it easier to reference. Here is an example
id = 1; (*first field name*) pop = 2; (*second field name*) name = 3; (*third field name*) (*now build the array of record, each row is a record*) m = {{1, 3000, "London"}, {1, 6000, "New York"}, {3, 7300, "Moscow"}}; (*now can iterate over the records*) Do[ Print@m[[i, id]]; m[[i, pop]] += 1, {i, Length[m]} ]
Ok, not very fancy, but easy to setup and data works with all M other functions, since it is just a list of lists.
Some more links on the subject
Remove[a, b, c, d, e, f] Apply[#1 + 3*#2 & , {{a, b}, {c, d}, {e, f}}, 1] Out[183]= {a + 3*b, c + 3*d, e + 3*f}
Or
Apply[#1 + 3*#2 & , {{a, b}, {c, d}, {e, f}}, {1}] Out[184]= {a + 3*b, c + 3*d, e + 3*f}
ListAnimate[Flatten[Reap[Do[Sow@Plot[Sin[x - c], {x, 0, 4 Pi}, Ticks -> None], {c, 0, 2 Pi - Pi/10, Pi/10}]]]]
Thanks to Alexey Popkov for this
SetOptions[EvaluationNotebook[], AutoStyleOptions -> {"CommentStyle" -> {FontWeight -> Plain, FontColor -> GrayLevel[0.6], ShowAutoStyles -> False, ShowSyntaxStyles -> False, AutoNumberFormatting -> False, FontFamily -> "Consolas"}}]
This came about when I was trying to convert 1/(1-x^2/2)
to normal form, i.e. tell
Mathematica to change the above to 1+x^2/2
But doing Simplify[1/(1-x^2/2)]
or
Expand
does not work. So the only solution I found is to use Series command, as
follows
Normal[Series[1/r, {x, 0, 2}]] Out[189]= 1 + x^2/2
Use these in parameter "declaration" of functions to make more robust. From the help
Clear[s]; f1 = 2/(s + 3); f2 = 7/(s^2 + 2.5*s + 7); Simplify[Together[f1 + f2]] Out[193]= (35. + 12.*s + 2.*s^2)/(21. + 14.5*s + 5.5*s^2 + s^3)
Options[myFun] = {form -> "linear"}; myFun[x_, OptionsPattern[]] := Module[{}, Print["x=", x, "form=", OptionValue[form]]; ] myFun[3, form -> "quadratic"]
This below is also a useful post by David Park on the net on options usage in packages
by Andrzej Kozlowski on math group, July 2010:
Suppose in the expression 2/3 I + x/y I
you wish to replace all fractions (that is 2/3
and x/y
) by r
and I
by d
. Without worrying about evaluation you can do this as
follows:
Unevaluated[Unevaluated[(2/3)*I + (x/y)*I] /. HoldPattern[(x_)/(y_)] -> r] /. HoldPattern[I] -> d Out[200]= -d + d*(1 - x^2/2)
If you allow the expression to evaluate the patterns will no longer match. For example, with only one Unevaluated you will get
Unevaluated[(2/3)*I + (x/y)*I] /. HoldPattern[(x_)/(y_)] -> r /. HoldPattern[I] -> d Out[201]= -I + I*(1 - x^2/2)
question: I want to replace y for x everywhere except in Exp[x].
Answer by Bob Hanlon on the net. messageID=7120881&tstart=0
Remove["Global`*"] expr = a*x + b*x^2 - c*Exp[x]; expr /. {Exp[x] -> z, x -> y} /. z -> Exp[x] Out[211]= (-c)*E^x + a*y + b*y^2
Block and Module have values, the last expression evaluated is their value, we can
see this by making a Grid (or just printing). But module leaked symbols have $
signs
Remove["Global`*"] Grid[{{Module[{x}, x]}}, Frame -> All]
Modules and Blocks both execute if they are in the path of code, without calling them. Block:
Remove["Global`*"] x = 4; Block[{}, If[x == 4, x = 3]]; x Out[217]= 3
Module:
Remove["Global`*"] x = 4; Module[{}, If[x == 4, x = 3]]; x Out[221]= 3
These are the steps I use to make TOC which is just HTML links to internal tags in the notebook, where these cell tags are sections. This way, when I exprt to HTML, I end up with TOC which is hyperlinks to internal locations within the web page.
Cell->Cell tags->Add/remove
and in the little window,
paste the title of the section there and click Add
.
Now, using the mouse again, select the text you just pasted, and do right-click and select MAKE hyperlink. This will bring up a menu like this
lst = {{x -> 4, y -> 7}, {x -> 2, y -> 5}, {x -> -1, y -> 10}}
one way
({#1[[1,2]], #1[[2,2]]} & ) /@ lst Out[223]= {{4, 7}, {2, 5}, {-1, 10}}
another way
Cases[lst, {_ -> n_, _ -> m_} :> {n, m}] Out[224]= {{4, 7}, {2, 5}, {-1, 10}}
One way us to use Item
mat = Table[Random[], {3}, {3}]; Framed[ Item[Grid[mat, Frame -> All, Alignment -> Center], Alignment -> {Center, Top}], ImageSize -> {300, 200}]
|
|
One way us to use Item
Grid[{{"row1,row1"}, {"row2"}, {"row3"}}, Frame -> All] Grid[{{"row1,row1"}, {Item["row2", Alignment -> Left]}, {"row3"}}, Frame -> All]
Use NumberForm
NumberForm[1./10^6, ExponentFunction -> (Null & )] Out[227] 0.000001
Sometimes I get the case that the notebook retain old definitions and symbols even after I
deleted them from the notebook. This happened when I was using a Demonstration
stylesheet and had an separate initilization cell, and had added SaveDefinitions->True
in
the Manipulate cell.
To make sure the notebook clears any old symbols, enter this command in the notebook once
SetOptions[EvaluationNotebook[], PrivateNotebookOptions -> {"FileContents" -> {"NotebookData"}, "FileOutlineCache" -> False}]
In addition, I change the preferences like this:
The call for each is as follows
A list has a Head at its zero index position
lst = {1, 2, 3}; Head[lst] Out[242]= List lst[[0]] Out[243]= List
By changing the head we use Apply. For example, to add the numbers of the above lst, we
need to change the Head from List to Plus. There is a command in Mathematica to change
the Head, called Apply
Plus @@ lst Out[244]= 6
We could have used the zero index trick, but it is better to use Apply:
lst[[0]] = Plus Out[245]= Plus lst Out[246]= 6
If we have a list of lists, like this
lst = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Out[247]= {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
And we wanted to change the head of each list in it, for example, we want the product of each list shown, then we need to change the head of each list to Times. To do that, the follwing short but might be strange looking command
Apply[Times, lst, {1}] Out[248]= {6, 120, 504}
Another way to do the above is to Map the Apply function
(Times @@ #1 & ) /@ lst Out[249]= {6, 120, 504}
or, little shorter version of the above:
(Times @@ #1 & ) /@ lst Out[250]= {6, 120, 504}
Mathematica default display of polynomial is reverse the traditional form:
poly = x^3 + a*x + b*x^2 + c + d Out[251]= 27 + 3*a + 9*b + c + d
use Traditional
Form with ParameterVariables
to make it appear as in text
books
TraditionalForm[poly, ParameterVariables :> {a, b, c, d}]
See this article by David Wagner http://www.mathematica-journal.com/issue/v6i2/columns/wagner/wagner62.pdf
And why-are-some-function-names-red
Some note here
Sort[]
sorts numbers from small to large by default. By supplying a function, one can
change this as needed
lst = {1, 2, 5, 3, 7}; Sort[lst] Out[255]= {1, 2, 3, 5, 7} Sort[lst, #1 < #2 & ] Out[256]= {1, 2, 3, 5, 7} Sort[lst, #1 > #2 & ] Out[257]= {7, 5, 3, 2, 1}
To find say all names in NDSolve and options used by that name if any do (this example is for NDSolve)
getList[name_String] := Module[{options, idx}, options = Names[name <> "`*"]; options = ToExpression /@ options; options = {#, Options[#]} & /@ options; idx = Range[Length[options]]; options = {#[[1]], TableForm[#[[2]]]} & /@ options; options = Insert[options[[#]], #, 1] & /@ idx; options = Insert[options, {"#", "Option", "Options to this option"}, 1]; Grid[options, Frame -> All, Alignment -> Left, FrameStyle -> Directive[Thickness[.005], Gray]] ];
then call it with
getList["NDSolve"]
It will produce large table. Here is part of it
getList["FindMinimum"]
if one types in 1,2,3,4
is there is a way to select these and have {}
automatically put
around them to make a list {1,2,3,4}
using escape key shortcut?
Answer by Chris Degnen who wrote this
FrontEndExecute[FrontEnd`AddMenuCommands["DuplicatePreviousOutput", {Delimiter, MenuItem["Make List", FrontEnd`KernelExecute[nb = SelectedNotebook[]; sel = NotebookRead[nb]; NotebookWrite[nb, Cell[BoxData[RowBox[{"{", sel, "}"}]]]]], MenuKey["u", Modifiers -> {"Control"}], MenuEvaluator -> Automatic]}]]
put it in the init file to load at start-up. See wrap-text-selection-in-brackets-in-mathematica
I needed to do this when I was parsing some output. The problem is like this: given a string
say "foo[] boo[] more goo[] more"
and wanted to look for pattern like this
"__["
In other words, a letter or more that end with "["
, but needed to find the first one. Hence in
the above, I wanted to find "foo"
.
2 ways to do this:
s = "foo[] boo[] more goo[] more"; StringCases[s, RegularExpression["^\\w*\\["]] Out[265]= {foo[}
and
StringCases[s, Shortest[StartOfString~~__~~"["], Overlaps -> False] Out[266]= {foo[}
Takes function and applies it to each element in a list
f /@ {a, b, c} Out[267]= {f[a], f[b], f[c]} (1 + g[#1] & ) /@ {a, b, c} Out[268]= {1 + g[a], 1 + g[b], 1 + g[c]} f /@ {a, b, c} Out[269]= {f[a], f[b], f[c]}
Use when function needs to be called with arguments taken from more than one list, else use Map if argument come from one list
Thread[f[{a, b, c}]] Out[270]= {f[a], f[b], f[c]} f /@ {a, b, c} Out[271]= {f[a], f[b], f[c]} Thread[f[{a, b, c}, {1, 2, 3}]] Out[272]= {f[a, 1], f[b, 2], f[c, 3]}
MapThread[f, {{a, b, c}, {1, 2, 3}}] Out[273]= {f[a, 1], f[b, 2], f[c, 3]}
In this case gives the same answer as using Thread
Thread[f[{a1, a2, a3}, {b1, b2, b3}]] Out[274]= {f[a1, b1], f[a2, b2], f[a3, b3]}
This is only when the lists are one level. For 2 levels we have to use MapThread. This shows the difference
MapThread[f, {{{a, b}, {c, d}}, {{1, 2}, {3, 4}}}] Out[275]= {f[{a, b}, {1, 2}], f[{c, d}, {3, 4}]} Thread[f[{{{a, b}, {c, d}}, {{1, 2}, {3, 4}}}]] Out[276]= {f[{{a, b}, {c, d}}], f[{{1, 2}, {3, 4}}]}
see tutorial/PatternsOverview
this below from tutorial/PuttingConstraintsOnPatterns
See also what-is-the-recommended-way-to-check-that-a-list-is-a-list-of-numbers-in-argumen
foo[(x_)?(Element[#1, Integers] & )] := x foo[x_Integer] := x foo[x_Integer] := x
foo[(x_)?(IntegerQ[#1] && #1 > 0 & )] := x foo[x_Integer /; x > 0] := x foo[(x_Integer)?Positive] := x foo[x_Integer /; x > 0] := x
foo[(x_)?(IntegerQ[#1] && #1 < 0 & )] := x foo[x_Integer /; x < 0] := x foo[(x_Integer)?Negative] := x foo[x_Integer /; x < 0] := x
foo[(x_)?(IntegerQ[#1] && #1 >= 0 & )] := x foo[x_Integer /; x >= 0] := x foo[(x_Integer)?NonNegative] := x foo[x_Integer /; x >= 0] := x
foo[(x_)?(IntegerQ[#1] && #1 <= 0 & )] := x foo[x_Integer /; x <= 0] := x foo[(x_Integer)?NonPositive] := x foo[x_Integer /; x <= 0] := x
foo[x_Integer /; x > 3 && x < 7] := x
foo[x_?(Element[#, Reals] &)] := x foo[x_Real] := x
foo[x_Real /; x > $MachineEpsilon] := x foo[x_Real /; x > $MachineEpsilon] := x foo[x_Real /; Positive[x]] := x foo[x_ (Element[#, Reals] && Positive[#] &)] := x
foo[x_Real /; x < $MachineEpsilon] := x foo[x_Real /; x < $MachineEpsilon] := x foo[x_Real /; Negative[x]] := x foo[x_?(Element[#, Reals] && Negative[#] &)] := x
foo[x_Real /; x >= $MachineEpsilon] := x foo[x_Real /; x >= $MachineEpsilon] := x foo[x_Real /; Positive[x] || x == 0] := x foo[x_ (Element[#, Reals] && (Positive[#] || # == 0) &)] := x
foo[x_Real /; x <= $MachineEpsilon] := x foo[x_Real /; x <= $MachineEpsilon] := x foo[x_Real /; Negative[x] || x == 0] := x foo[x_ (Element[#, Reals] && (Negative[#] || # == 0) &)] := x
foo[x_ (Element[#, Reals] && ((# - 3) > $MachineEpsilon && (7 - #) > $MachineEpsilon) &)] := x foo[x : _Real /; (x - 3) > $MachineEpsilon && (7 - x) > $MachineEpsilon] := x
foo[x_?(Element[#, Booleans] &)] := x
foo[x_?(Element[#, Reals] &)] := x foo[x_?(NumericQ[#] &)] := x foo[x : _?NumericQ] := x
foo[x_?(NumberQ[#] &)] := x
foo[x_Complex] := x foo[x_?(Not@FreeQ[#, _Complex] &)] := x
foo[x_List] := x
foo[x_?(VectorQ[#] &)] := x
foo[x_?(VectorQ[#, NumericQ] &)] := x
foo[x_?(VectorQ[#, NumericQ] &)] := x foo[x : {_?NumericQ ..}] := x foo[x : {__?NumericQ }] := x foo[x_?(VectorQ[#, IntegerQ] &)] := x
foo[x_?(MatrixQ[#, NumericQ] &)] := x foo[x : {{_?NumericQ ..}}] := x foo[x : {{__?NumericQ }}] := x
foo[x_?(MatrixQ[#, NumericQ] && FreeQ[#, _Complex] &)] := x
foo[x_?(MatrixQ[#, StringQ] &)] := x
use MatchQ
MatchQ[1/3, _Rational] Out[277]= True MatchQ[3, _Integer] Out[278]= True Or for the above can do IntegerQ[3] Out[279]= True
Grid[{ {Item[a, Alignment -> Center], b}, {SpanFromAbove, c}}, Frame -> All] Grid[{ {Item[a, Alignment -> Center], Item[Column[{b, c}]]}}, Frame -> All] Grid[{ {Item[a, Alignment -> Center], Item[Column[{b, c}, Frame -> All]]}}, Frame -> All] Grid[{ {a, Item[b, Alignment -> Center]}, {c, SpanFromAbove}}, Frame -> All] Grid[{ {Item[a, Alignment -> Center], Item[b, Alignment -> Center], c}, {SpanFromAbove, SpanFromAbove, d}, {SpanFromAbove, e, f}}, Frame -> All]
From help
See select-and-blank
test = {{"String1", "a"}, {"String2", "b"}, {"String3", "a"}, {"String4", "a"}}; Cases[test, {_String, "a"}] Out[281]= {{String1, a}, {String3, a}, {String4, a}} Select[test, MatchQ[#1, {_String, "a"}] & ] Out[282]= {{String1, a}, {String3, a}, {String4, a}}
See given-a-symbolic-expression-how-to-find-if-starts-with-a-minus-or-not
Clear[x] p = (_.)*_?Negative; MatchQ[-3*x^2, p] Out[285]= True MatchQ[3*x^2, p] Out[286]= False expr = -3*x^2; (expr /. Thread[Variables[expr] -> 1]) < 0 Out[288]= True expr = 3*x^2; (expr /. Thread[Variables[expr] -> 1]) < 0 Out[290]= False
Watch out for adding the extra third argument to trigger as show below (which is 1 now). This seems to cause a problem. Was using it in Manipulate and when I added, sometimes the trigger stops firing on its own. When I remove it, it never does stop.
Trigger[Dynamic[t0, {t0 = #} &], {0, 10000, 1}, ....] ToString[#] & /@ a| is same as ToString /@ a
see how-to-select-and-delete-all-output-cells
To make a matrix, which contains on its diagonal matrices, Matlab uses the command
blkdiag
. In Mathematica use the following
a = {{1, 2, 3}, {4, 5, 6}} b = {{7, 8}, {9, 10}} SparseArray[Band[{1, 1}] -> {a, b}]
Below is from "accuracy and stability of numerical algorithms", by Highma, page 36
ClearAll["Global`*"] lst = {{a, b}, {c, d}}; MapThread[f, lst] Out[14]= {f[a, c], f[b, d]} Thread[f[Sequence @@ lst]] Out[15]= {f[a, c], f[b, d]}
ClearAll[x, y, z, g, foo]; p1 = Conjugate[x_]*Conjugate[y_] :> Conjugate[x*y]; p2 = (x_)*Conjugate[x_] :> Abs[x]^2; p3 = Abs[(x_)*(y_)]^(n_.) :> Abs[x]^n*Abs[y]^n; p4 = (x_)*Conjugate[y_] + (y_)*Conjugate[x_] :> 2*(Re[x]*Re[y] + Im[x]*Im[y]); p5 = (x_) + Conjugate[x_] :> 2*Re[x]; allRules = {p1, p2, p3, p4, p5};
test it
expr = {{foo = x*Conjugate[y] + y*Conjugate[x]; foo, foo //. allRules}, {foo = x*Conjugate[y] + y*Conjugate[x] + z*Conjugate[g] + g*Conjugate[z]; foo, foo //. allRules}, {foo = x*Conjugate[x]; foo, foo //. allRules}, {foo = x*y*Conjugate[x*y]; foo, foo //. allRules}, {foo = x*y*z*Conjugate[x*y*z]; foo, foo //. allRules}, {foo = x + Conjugate[x]; foo, foo //. allRules}, {foo = x*y + Conjugate[x*y], foo; foo //. allRules}, {foo = x*y*z + Conjugate[x*y*z]; foo, foo //. allRules}, {foo = x*y + Conjugate[x]*Conjugate[y]; foo, foo //. allRules}, {foo = x*y*z*g + Conjugate[x]*Conjugate[y]*Conjugate[z]*Conjugate[g]; foo, foo //. allRules}}; Grid[expr, Frame -> All, Spacings -> {0.5, 1}, Alignment -> Left]
See mathematica/guide/ListingOfNamedCharacters.html
From extract-values-for-viewmatrix-from-a-graphics3d/3538
by Yu-Sung Chang (Wolfram Research)
eq = E^(0.002/t) + E^(0.032/t) == 2*E^(0.03/t) Thread[Log[eq], Equal] Out[26]= Log[E^(0.002/t) + E^(0.032/t)] == Log[2*E^(0.03/t)]
Watch out when defining a function such as this:
f[x_] := Integrate[x - t, {t, 0, x}]
The problem is this:
In[45]:= f[t] Out[45]= 0
This is becuase the replacement of "x" by "t" changed the integrand to zero.
The correct way is to always use Module symbols for everything inside the function, like this
f[x_] := Module[{t}, Integrate[x - t, {t, 0, x}]]
Now it gives the correct answer regardless of the symbol used as argument
In[46]:= f[t] Out[46]= t^2/2 In[47]:= f[x] Out[47]= x^2/2
StringCases[#, ___ ~~ "Distribution" ~~ ___ :> #] & /@ Names["System`*"]; DeleteCases[%, {}]
Gives
{{"ArcSinDistribution"}, {"BarabasiAlbertGraphDistribution"}, {"BatesDistribution"}, {"BeckmannDistribution"}, \ {"BenfordDistribution"}, {"BeniniDistribution"}, {"BenktanderGibratDistribution"}, {"BenktanderWeibullDistribution"}, \ {"BernoulliDistribution"}, {"BernoulliGraphDistribution"}, {"BetaBinomialDistribution"}, {"BetaDistribution"}, \ {"BetaNegativeBinomialDistribution"}, {"BetaPrimeDistribution"}, {"BinomialDistribution"}, {"BinormalDistribution"}, \ {"BirnbaumSaundersDistribution"}, {"BorelTannerDistribution"}, {"CauchyDistribution"}, {"CensoredDistribution"}, \ {"ChiDistribution"}, {"ChiSquareDistribution"}, {"CompoundPoissonDistribution"}, {"CopulaDistribution"}, {"CoxianDistribution"}, \ {"DagumDistribution"}, {"DataDistribution"}, {"DavisDistribution"}, {"DegreeGraphDistribution"}, {"DirichletDistribution"}, \ {"DiscreteUniformDistribution"}, {"DistributionChart"}, {"DistributionDomain"}, {"DistributionFitTest"}, \ {"DistributionParameterAssumptions"}, {"DistributionParameterQ"}, {"EmpiricalDistribution"}, {"ErlangDistribution"}, \ {"EstimatedDistribution"}, {"ExpGammaDistribution"}, {"ExponentialDistribution"}, {"ExponentialPowerDistribution"}, \ {"ExtremeValueDistribution"}, {"FailureDistribution"}, {"FindDistributionParameters"}, {"FirstPassageTimeDistribution"}, \ {"FisherHypergeometricDistribution"}, {"FisherZDistribution"}, {"FRatioDistribution"}, {"FrechetDistribution"}, \ {"GammaDistribution"}, {"GeometricDistribution"}, {"GompertzMakehamDistribution"}, {"GraphPropertyDistribution"}, \ {"GumbelDistribution"}, {"HalfNormalDistribution"}, {"HistogramDistribution"}, {"HotellingTSquareDistribution"}, \ {"HoytDistribution"}, {"HyperbolicDistribution"}, {"HyperexponentialDistribution"}, {"HypergeometricDistribution"}, \ {"HypoexponentialDistribution"}, {"InverseChiSquareDistribution"}, {"InverseGammaDistribution"}, {"InverseGaussianDistribution"}, \ {"JohnsonDistribution"}, {"KDistribution"}, {"KernelMixtureDistribution"}, {"KumaraswamyDistribution"}, {"LandauDistribution"}, \ {"LaplaceDistribution"}, {"LevyDistribution"}, {"LindleyDistribution"}, {"LogGammaDistribution"}, {"LogisticDistribution"}, \ {"LogLogisticDistribution"}, {"LogMultinormalDistribution"}, {"LogNormalDistribution"}, {"LogSeriesDistribution"}, \ {"MarginalDistribution"}, {"MaxStableDistribution"}, {"MaxwellDistribution"}, {"MeixnerDistribution"}, {"MinStableDistribution"}, \ {"MixtureDistribution"}, {"MoyalDistribution"}, {"MultinomialDistribution"}, {"MultinormalDistribution"}, \ {"MultivariateHypergeometricDistribution"}, {"MultivariatePoissonDistribution"}, {"MultivariateTDistribution"}, \ {"NakagamiDistribution"}, {"NegativeBinomialDistribution"}, {"NegativeMultinomialDistribution"}, {"NoncentralBetaDistribution"}, \ {"NoncentralChiSquareDistribution"}, {"NoncentralFRatioDistribution"}, {"NoncentralStudentTDistribution"}, {"NormalDistribution"}, \ {"OrderDistribution"}, {"ParameterMixtureDistribution"}, {"ParetoDistribution"}, {"PascalDistribution"}, {"PearsonDistribution"}, \ {"PERTDistribution"}, {"PoissonConsulDistribution"}, {"PoissonDistribution"}, {"PolyaAeppliDistribution"}, {"PowerDistribution"}, \ {"PriceGraphDistribution"}, {"ProbabilityDistribution"}, {"ProductDistribution"}, {"RayleighDistribution"}, \ {"ReliabilityDistribution"}, {"RiceDistribution"}, {"SechDistribution"}, {"SinghMaddalaDistribution"}, {"SkellamDistribution"}, \ {"SkewNormalDistribution"}, {"SliceDistribution"}, {"SmoothKernelDistribution"}, {"SpatialGraphDistribution"}, \ {"SplicedDistribution"}, {"StableDistribution"}, {"StandbyDistribution"}, {"StationaryDistribution"}, {"StudentTDistribution"}, \ {"SurvivalDistribution"}, {"SuzukiDistribution"}, {"TransformedDistribution"}, {"TriangularDistribution"}, \ {"TruncatedDistribution"}, {"TsallisQExponentialDistribution"}, {"TsallisQGaussianDistribution"}, {"TukeyLambdaDistribution"}, \ {"UniformDistribution"}, {"UniformGraphDistribution"}, {"UniformSumDistribution"}, {"VarianceGammaDistribution"}, \ {"VoigtDistribution"}, {"VonMisesDistribution"}, {"WakebyDistribution"}, {"WalleniusHypergeometricDistribution"}, \ {"WaringYuleDistribution"}, {"WattsStrogatzGraphDistribution"}, {"WeibullDistribution"}, {"WignerSemicircleDistribution"}, \ {"ZipfDistribution"}}
see how-to-return-the-value-of-automatic-when-it-is-used-in-a-mathematica-function
Thanks to Bob Hanlon for this method:
p1 = Plot[Sin[x], {x, 0, Pi}, PlotPoints -> Automatic] Cases[p1, Line[pts_] :> Length[pts], Infinity] (*259*)
Another method due to Simon Woods
Trace[ Plot[Sin[t], {t, 0, 2 Pi}], HoldPattern[PlotPoints | MaxRecursion -> _], TraceInternal -> True] // Flatten // Union {MaxRecursion -> 6, MaxRecursion -> Automatic, PlotPoints -> 50, PlotPoints -> Automatic}
make sure to copy the notebook first, just in case.
Module[{nb}, nb = EvaluationNotebook[]; NotebookFind[EvaluationNotebook[], "Input", All, CellStyle]; NotebookDelete[nb]]
To understand what it does, these three do the same thing
Map[If[# == 1, Unevaluated@Sequence[], #] &, {1, 2, 3}]; If[# == 1, Unevaluated@Sequence[], #] & /@ {1, 2, 3}; If[# == 1, Sequence @@ {}, #] & /@ {1, 2, 3}; If[# == 1, ## &[], #] & /@ {1, 2, 3};
All above give {2,3}
. So the effect of ## &[]
is to remove the entry completely (so we do not
end up with a Null or empty slot in there).
Given lists a={1,2,3}, b={4,5,6}
and we want to do operation from slot 1 from a with slot
1 from b, and so on. For this, we can use ‘MapThread‘. Suppose we want to add each
corresponding slot, then
a = {1, 2, 3} b = {4, 5, 6} MapThread[(#1 + #2) &, {a, b}] (* {5, 7, 9} *)
Of course, in this simple example, doing a+b
will work, but this is just an example.
see https://mathematica.stackexchange.com/questions/5212/automating-esc-esc-formatting
>sudo bash Mathematica_10.1.0_LINUX.sh [sudo] password for me: Mathematica 10.1.0 for LINUX Installer Archive Verifying archive integrity. Extracting installer. ............. Wolfram Mathematica 10.1 Installer Copyright (c) 1988-2015 Wolfram Research, Inc. All rights reserved. WARNING: Wolfram Mathematica is protected by copyright law and international treaties. Unauthorized reproduction or distribution may result in severe civil and criminalpenalties and will be prosecuted to the maximum extent possible under law. Enter the installation directory, or press ENTER to select /usr/local/Wolfram/Mathematica/10.1: Now installing... [****************** Type the directory path in which the Wolfram Mathematica script(s) will be created, or press ENTER to select /usr/local/bin: > Installation complete. >which Mathematica /usr/local/bin/Mathematica >export DISPLAY=:0 >Mathematica
One method is to just type WolframAlpha["command here"]
and then click on the
show step by step
on top right corner of the result that displays on the notebook,
assuming Wolfram Alpha gives an answer.
If the above does not work, try
WolframAlpha["Integrate[x Sin[x],{x,0,Pi}]", {{"Input", 2}, "Content"}, PodStates -> {"Input__Step-by-step solution"}]
Another example
WolframAlpha["solve y''=-y", IncludePods -> "DifferentialEquationSolution", AppearanceElements -> {"Pods"}, TimeConstraint -> {20, Automatic, Automatic, Automatic}, PodStates -> {"DifferentialEquationSolution__Step-by-step solution"}]
or for text output
WolframAlpha["solve y''=-y", {{"DifferentialEquationSolution", 2}, "Plaintext"}, PodStates -> {"DifferentialEquationSolution__Step-by-step solution"}]
Another example
WolframAlpha["q*c'[x]==k*c[x], c[0]==c0", PodStates -> {"Step-by-step solution"}]
see http://mathematica.stackexchange.com/questions/15480/how-do-i-designate-arguments-in-a-nested-map
From about url by Halirutan:
Map[Function[p2, Map[Function[p1, f[p1, p2]], list1]], list2]
How to make TeXForm handle higher derivatives better.
See http://mathematica.stackexchange.com/questions/134936/texform-handling-of-derivative-higher-than-two
From above URL by Carl Woll
Derivative /: MakeBoxes[Derivative[n_Integer?Positive][h_],TraditionalForm] := SuperscriptBox[MakeBoxes[h,TraditionalForm], StringJoin@ConstantArray["\[Prime]",n] ] TeXForm[y'''''[t] + 2 x'''[t] - y'[t] == x[t]]
sometime code is posed at Mathematica stacexchange which is hard to read. To convert it to clear 2D math code, copy into a mathematica cell (in an open notebook) on the computer, then do
CTRL-SHIFT-N
Given
Replace only the subexpression of the form anything*Exp[anyting]*Sqrt[anything]
by the square of the pattern found if any.
expr /. patternName : (Exp[any3_]*any_.)*Power[Any_, Rational[1 | -1, 2]] -> patternName^2
This gives
The code patternName :
above gives a name for the pattern found, this way we can use
the name to easily do any transformation needed. In this example, it was just squaring it.
But it can be anything else we want.
Optional arguments are very important and useful. It is easy to make these in Mathematica.
lets say we want to make function foo
that takes person name and age but the sex is
provided as optional with default value as say male
. To do this, two things are needed to be
defined.
The function foo
itself, but with additional argument called opt : OptionsPattern[{foo}]
and we need to define an Options[foo] =...
which sets up the default values. Here is an
example
Clear["Global`*"]; (*this sets up the DEFAULT values for each optional argument *) Options[processPerson] = {"sex" -> "male"}; (*this is the definition of the function itself*) processPerson[name_String, age_?NumericQ, opt : OptionsPattern[{processPerson}]] /; age > 0 := Module[{sexOfPerson}, (* the following line reads the optional value sex->"" if provided *) (* else Mathematica will automatically return the default value set up*) sexOfPerson = OptionValue["sex"]; Print["Name = ", name]; Print["age = ", age]; Print["sex = ", sexOfPerson] ]
Now we are ready to call the function.
processPerson["me",10]
Gives
Name = me age = 10 sex = male
We see in the above, that variable sex
was automatically set to the default value thanks to
the definitions Options[foo]=...
Now we call it with explicitly passing in the optional argument
processPerson["me",10,"sex"->"female"]
Gives
Name = me age = me sex = female
In the above, the option argument sex->"..."
must always be the last one passed in. You
can not do this for example
processPerson["joe doe","sex"->"female",10]
Here is another example
Clear["Global`*"]; Options[dsolve] = {"ic" -> {}, "hint" -> "None"}; dsolve[ode_, y_[x_], x_, OptionsPattern[]] := Module[{ic = OptionValue["ic"], hint = OptionValue["hint"]}, Print["ic=", ic, " hint=", hint] ]; dsolve[y''[x] + y[x] == 1, y[x], x, "ic" -> {x[0] == 1}] dsolve[y''[x] + y[x] == 1, y[x], x] dsolve[y''[x] + y[x] == 1, y[x], x, "hint" -> "linear", "ic" -> {x[10] == 0}]
Which prints
ic={x[0]==1} hint="None" ic={} hint="None" ic={x[10]==0} hint="linear"
To find all options supported by function do as an example Options[LinearSolve]
and that
will print {Method -> Automatic, Modulus -> 0, ZeroTest -> Automatic}
It is better to use string for the name of the hint as in the above, so not to clash with the same symbol being already defined.
The above showed how to use optional value. This below shows how to check and what to do if an optional value was not what is expected. This is done by explicitly checking, after reading the optional value, that its value is one that is expected. Like this
Clear["Global`*"]; Options[processPerson]={"sex"->"male"}; processPerson::msg="`1`"; processPerson[name_String,age_?NumericQ,opt:OptionsPattern[{processPerson}]]/;age>0:=Module[{sex}, sex = OptionValue["sex"]; If[Not[MemberQ[{"male","female"},sex]], Message[processPerson::msg,"Invalid value for sex found. "<>sex<>" but expected one of {\"male\", \"female\"}"]; Abort[] ]; Print["Name = ",name]; Print["age = ",age]; Print["sex = ",sexOfPerson] ]
Now we are ready to call the function. Lets call it with bad value for the optional parameter
processPerson["me",10,"sex"->"car"] processPerson::msg: Invalid value for sex found. car but expected one of {"male", "female"} $Aborted
Copy the Mathematica code from the notebook, paste it into http://steampiano.net/msc/ and click convert. Then copy the output and paste that into the post at stackexchange.
Clear["Global`*"]; expr = y[z] + x + Pi + m/Sin[a] + b[0]; DeleteDuplicates@Cases[expr, any_ /; Head[any] === Symbol && Not[MemberQ[Attributes[any], Constant]], Infinity]
Gives {x,n,a,x}
. Note that the above does not detected indexed variables, such as \(b[0]\). The
Attributes
check is so not to include \(\pi \) since this is also a symbol. But we do not want to be
there.