Skip to main content

Posts

Showing posts from November, 2016

differential equations - WhenEvent in NDSolve

How come this doesn't work as I intended? s[{x0_, y0_}, a_, v_] := NDSolveValue[{ x'[t] == vx[t], WhenEvent[x[t] > 0, vx[t] -> -vx[t]], y'[t] == vy[t] - t, WhenEvent[y[t] < 0, vy[t] -> -vy[t]], x[0] == x0, vx[0] == v Cos@a, y[0] == y0, vy[0] == v Sin@a}, {x[t], y[t]}, {t, 0, 10}, DiscreteVariables -> {vx, vy}] Simulating falling and bouncing of a 2D mass point. With[{r0 = {-5, 7}}, ParametricPlot[Evaluate@s[r0, -.9, 2], {t, 0, 10}, PlotRange -> {{-10, 10}, {-10, 10}}, Epilog -> {Point@r0}]] I can't understand why it doesn't bounce on the x-axis first, and what does happen there anyway? Event x[t]>0 works fine. Following help I started with lowering the order of equations (and so doubling the number of variables). Here I wrote the equations in a more familiar 2nd order; everything works as expected. I put the function below in a tiny loop which bisected the right initial velocity v0 that returns the ball in its starti

Granular versus terse coding

While reading Leonid's grand answers to General strategies to write big code in Mathematica? I came across something that goes against my own practices. I do not disagree with the principle but the degree to which it is taken feels both alien and counterproductive to me. Quite possibly Leonid is right, he usually is, but I wish to indulge in a counterargument even if it ultimately only proves his point. He gives as his example of granular coding this: ClearAll[returnedQ,randomSteps,runExperiment,allReturns,stats]; returnedQ[v_,steps_]:=MemberQ[Accumulate[v[[steps]]],{0,0}]; randomSteps[probs_,q_]:=RandomChoice[probs->Range[Length[probs]],q]; runExperiment[v_,probs_,q_]:= returnedQ[v,randomSteps[probs,q]]; allReturns[n_,q_,v_,probs_]:= Total @ Boole @ Table[runExperiment[v,probs,q],{n}] stats[z_,n_,q_,v_,probs_]:=Table[allReturns[n,q,v,probs],{z}]; I have expressly left out the explanatory comments. Answering questions on Stack Exchange has taught me that code often doesn't

symbols - Is there a way to separate variables between multiple notebooks?

I often correct homework by checking the calculations in Mathematica. Sometimes you would like to have two solutions open at once. However often defined symbols such as f or phi regularly overlap between the two notebooks. Is there a way to separate them other than using different symbols in every notebook? Is it possible to separate some variables yet share others between notebooks? Answer May be this, I have not tried it, but it sounds like this is what you are looking for (if I understood you correctly): Evaluation menu -> Notebook's Default Context -> Unique to This Notebook. So, you do the above for each notebook. I found this in the daily Mathematica tip webpage: http://twitter.com/mathematicatip Update If you want to do it programatically from within a notebook, run SetOptions[EvaluationNotebook[], CellContext -> Notebook] . Update 2 To set this automatically for all new notebooks, open the Options Inspector ( Ctrl/Command + Shift + O ), and change the scope to

plotting - Combine Plots into a single non-rasterized Graphic with no spacing

Suppose that I have two plots, pl1 and pl2 : pl1 = Plot[x, {x, 0, 1}, Frame -> True, ImageSize -> 350] pl2 = Plot[x^2, {x, 0, 1}, Frame -> True, ImageSize -> 350] I would like to (1) combine these plots side-by-side in a (2) non-rasterized graphic with (3) no spacing . I get pretty close to my desired result by using Grid with Spacings -> 0 : Grid[{{pl1, pl2}}, Spacings -> 0] The above satisfies my requirements (2) and (3) : the result is non-rasterized , and there is no spacing between the plots. However, the above doesn't satisfy my requirement (1) , that the plots be combined into a single Graphic object. That is, if I click on either of the plots, I see that they are separate Graphic objects: So the above approach doesn't satisfy all of my requirements. (Why do I need the plots to be combined in a single Graphic ? The reason is that I want to be able to place other Graphic objects -- e.g., text, arrows, shapes, etc. -- that span the two plots.)

Sorting function for non commuting bosons

I am trying to write a sorting function which will sort expressions involving products of bosonic objects which do not commute. For example, I can have objects like $a,\ a^\dagger,\ b,\ b^\dagger$ where $[a,a^\dagger] = 1$, $[b,b^\dagger] = 1$ and all other commutators vanish. So the sorting function should for example sort a term like $a a^\dagger b a b^\dagger$ to $a + a^\dagger a^2 + ab^\dagger b+a^\dagger a^2 b^\dagger b$. So I want to sort them first lexicographically and then such that dagger objects will be to the left. I have been using a function from the notebook provided by Simon Tyler at arXiv . So I have created a bosonic object using Clear[Boson, BosonC, BosonA] Boson /: MakeBoxes[ Boson[cr : (True | False), sym_], fmt_] := With[{sbox = If[StringQ[sym], sym, ToBoxes[sym]]}, With[{abox = If[cr, SuperscriptBox[#, FormBox["\[Dagger]", Bold]], #] &@sbox}, InterpretationBox[abox, Boson[cr, sym]] ] ] BosonA[sym_:"a"] := Boson[False, sym] B

plotting - Harvested prey–predator model incorporating a prey refuge

I want to plot the phase diagram of prey predator versus prey refuge to see how the prey refuge influences the population of prey and predator. And this is the system $x'=\alpha x(1-x/k)-\beta\frac{(1-m)xy}{1+a(1-m)x}-q_1E_1x$ $y'=-\gamma y+c\beta\frac{(1-m)xy}{1+a(1-m)x}-q_2E_2y$ The prey predator with Holling type II model is incorporating a prey refuge, $mx$ and $k$, $\alpha$, $\gamma$, $c$ and $\beta/\alpha$ are the carrying capacity, growth rate of prey, death rate of predator, conversion factor denoting the number of newly born predators for each captured prey and maximum number of prey that can be eaten by each predator in unit time respectively. I have the numerical value for $a=0.02$, $k=100$, $\alpha=10$, $\beta=0.6$, $\gamma=0.09$, $c=0.02$. Thanks so much!

plotting - 4-dimensional Lotka-Volterra plot

I was referring to the question I posted earlier in Mathematics forum , but then I came to see this example on Wikipedia . How did they plot the system in phase space? The closet relevant topic I have done is the Lorenz Equation, where I used NDSolve and then ParametricPlot3D evaluated at the fix points. Answer Here's how to numerically solve the model. nsp = 4; {r[1], r[2], r[3], r[4]} = {1, 0.72, 1.53, 1.27}; {k[1], k[2], k[3], k[4]} = {1, 1, 1, 1}; amat = {{1, 1.09, 1.52, 0}, {0, 1, 0.44, 1.36}, {2.33, 0, 1, 0.47}, {1.21, 0.51, 0.35, 1}}; Do[a[i, j] = amat[[i, j]], {i, nsp}, {j, nsp}]; eqns = Table[x[i]'[t] == r[i]*x[i][t]*(1 - Sum[a[i, j]*x[j][t]/k[i], {j, nsp}]), {i, nsp}]; ics = Table[x[i][0] == 0.1, {i, nsp}]; unks = Table[x[i], {i, nsp}]; tmax = 10000; sol = NDSolve[{eqns, ics}, unks, {t, 0, tmax}][[1]]; ParametricPlot3D[Evaluate[{x[1][t], x[2][t], x[3][t]} /. sol], {t, 100, tmax}, AxesLabel -> {"x1", "x2", "x3"}, PlotPoints ->

function construction - How to directly/conveniently use variable names as filenames?

Purpose To use variable name as file name conveniently. Code Special thanks to @J.M.'s tips! Remove@"Global`*" p = Plot[#, {x, 0, 1}] & /@ {x, 1/x}; SetAttributes[g, HoldAll] g[p_] := Export[ToString@Unevaluated@p <> ".png", p] (* Few images: *) {g@p[[1]], g@p[[2]]} (* Many images: *) g /@ Hold @@ Table["p[[" <> ToString@i <> "]]", {i, Length@p}] // ToString // ToExpression // ReleaseHold Question I'm not satisfied with this two lines in the last section of the above code: Table["p[[" <> ToString@i <> "]]", {i, Length@p}] // ToString // ToExpression I believe there are smarter ways to implement that, please teach me, thanks! Answer Maybe something in this line might do: SetAttributes[ g, HoldFirst ]; g[ sym_ ] := With[ { baseFileName = SymbolName @ Unevaluated @ sym, ext = ".png" }, Switch[ sym, { __Graphics }, Range@Length@sy

plotting - How to scale values for ColorFunction in SliceContourPlot3D?

Trying to help out in the question, Finite Elements 3D , I came across this behavior of SliceContourPlot3D : op = -Laplacian[u[x, y, z], {x, y, z}] - 2; uif = NDSolveValue[{op == 0, DirichletCondition[u[x, y, z] == 0, True}, u, {x, y, z} ∈ Ball[{0, 0, 0}]]; SliceContourPlot3D[ uif[x, y, z], "CenterPlanes", {x, y, z} ∈ MeshRegion@uif["ElementMesh"], ColorFunction -> "Rainbow"] The range of colors does not go all the way down to violet/indigo. I expected the range of colors to be something like this: With[{sel = Positive[uif["Grid"].{0.3, -0.4, -1}]}, With[{pts = Pick[uif["Grid"], sel]}, Graphics3D[ GraphicsComplex[ pts, {Point[Range@Length@pts, VertexColors -> (ColorData["Rainbow"] /@ Rescale[Pick[uif["ValuesOnGrid"], sel]]) ]} ]] ]] Is this a bug in SliceContourPlot3D ? (Perhaps it's due to extrapolation from sampling outside the domain?) Is there a way to get it to resc

list manipulation - subtraction of Y values

I have two lists (first one is data, second one is background) of files that are composed of X and Y coordinates. X coordinates are the same for both lists. I would like to subtract the y coordinates of corresponding files (A1-A2, B1-B2, etc) for whole data set. Is there a quick way to do it? data1 is composed of {a1.txt, a2.txt} and data2 of{b1.txt,b2.txt} I can only imagine doing a small for loop in which I use following code: data1[[1]][[All, 2]] - data2[[1]][[All, 2]] and then I MapThread X and new Y coordinate. data1[[1]] X Y1 0.008362 837448.1111 0.028126 23665.24245 0.048397 2174.605716 0.068667 528.9201242 0.088938 205.8876254 0.109208 98.85484604 0.129477 65.01622775 0.149746 43.40275276 0.170015 35.06444229 0.190282 25.51391261 0.200416 21.10450766 data2[[1]] X Y4 0.008362 0.008166246 0.028126 0.02746757 0.048397 0.047264026 0.068667 0.067059506 0.088938 0.086855961 0.109208 0.106651441 0.129477 0.126445943 0.149746

web access - Using URLExecute to login to website

One of my students is doing summer research for a local company to help analyze some of their data. Trouble is, the web interface they provide for downloading the data only allows one to download one customer's info at a time; there are over 3000 customers to analyze. I'd like to use Mathematica (MMA) to automate this process. Step 1: use MMA to log in to their website. I've looked at many similar posts and still struggle to understand how to use Import or URLFetch or URLExecute to accomplish this. I can't share the company's URL, though from the page source this seems to be the relevant code: Please sign in Sign in I tried using URLExecute["https://THEIR_WEB_ADDRESS.com/src/index.php?page=admin", {"username" -> "fooUser", "password" -> "fooPassword"}] but the response seems to indicate the website doesn't understand the requested page. I also tried variations of "Username" vs "username&qu

binary - HMAC implementation in pure Mathematica

I am trying to implement the HMAC algorithm in Mathematica. The algorithm is a relatively simple way of signing messages with a key. Here is some pseudocode from Wikipedia: My attempt: hash[string_String, method_String : "SHA256"] := FromCharacterCode @ Interpreter["HexInteger"] @ StringPartition[IntegerString[Hash[string, method], 16], 2]; HMAC[key_String, message_String, method_String : "SHA256", blockSize_Integer : 64] := Module[ {char54, char92, key2, ipad, opad}, {char54, char92} = FromCharacterCode /@ {54, 92}; key2 = Switch[StringLength @ key, blockSize, key, l_ /; l > blockSize, hash[key, method], _, StringPadRight[key, blockSize, FromCharacterCode @ 0]]; ipad = FromCharacterCode[BitXor @@ Map[ToCharacterCode, {StringRepeat[char54, blockSize], key2}]]; opad = FromCharacterCode[BitXor @@ Map[ToCharacterCode, {StringRepeat[char92, blockSize], key2}]]; hash @ StringJoin[opad, hash @ StringJoi

customization - How to get old message formatting in version 11?

Version 11 uses a new-style message formatting. The new style has useful features, and it is usually desirable. However, when saved in a notebook, it doesn't display correctly in older versions of Mathematica . If we use version 11 to write documentation for a package that is also compatible with older versions, we cannot include new-style messages in the notebook. How can we turn off this new message formatting? Answer We can get old-style messages using Internal`$MessageMenu = False Needless to say, this is unsupported and undocumented functionality.

documentation - How to get a list of available appearance/styles/Methods?

This is a basic question but I haven't found any answer yet :/ Available appearances for Button[] are mentioned in Help , those are "Palette" , "FramedPalette" , "DialogBox" and so on. But is this all? How could I get to know? For example there is also used in Help "NoOp" option in MouseAppearance[] . Are there any others in addition to those mentioned in Help . Is there somewhere more info about styles but for different functions too? Answer This answer in not the answer you want. There are almost certainly more options for a button's appearance than are documented in the Help Center. As far a I know there is no way to discover what appearance options apply to buttons. This seems to be a deliberate policy on the part of WRI. I recently had a exchange of email with WRI tech suppor on a related matter, SetterBar . This was their position on that subject: Many functions like SetterBar have optional arguments available which are not doc

notebooks - How can I automatically name files being exported based on input parameters

I have Mathematica notebook that performs some operation say a=2 b=3 c=5 d=4 how do I set the output file after evaluation to be named using the values $2,3,5,\ldots$ like "2_3_5_4_" such that the the naming automatically takes the values assigned to a,b,c d Answer Your data {a, b, c, d} = RandomInteger[9, 4]; data = a b c d; Exporting with nice file-names featuring date and variable values using StringTemplate Export[ StringTemplate[ "Date`1`_Values_a`2`_b`3`_c`4`.txt" ][DateString[{"Year", "Month", "Day"}], a, b, c] , data] "Date20141201_Values_a7_b5_c3.txt" Or using ToString and StringJoin as suggested by @Kuba Export[ StringJoin["Data_", ToString /@ Riffle[{a, b, c, d}, "_"], ".txt"] , data] "Data_7_5_3_7.txt"

plotting - How to avoid axis inversion by DataRange when used in Arrayplot?

Working on Mathematica 11.3, I find that the vertical axis (more precisely its ticks) is reversed by DataRange which should not happen, e.g. nmax = 100; ArrayPlot[Table[x + y, {x, 0, nmax}, {y, 0, nmax}], PlotLegends -> True, FrameTicks -> Automatic] ArrayPlot[Table[x + y, {x, 0, nmax}, {y, 0, nmax}], PlotLegends -> True, FrameTicks -> Automatic, DataRange -> {{0, nmax}, {0, nmax}}] Resulting in I want a plot like in the first picture but with arbitrarily chosen DataRange and do not want to have the data reversed along the vertical direction (as in ListDensityPlot ). Both axes should start at the top left corner. I found a workaround using manual setting of frame ticks but that is not nice. Is their a simple solution? Answer This is a non-intuitive, but expected behavior. It just comes down to how do you interpret DataRange . See the additional option DataReversed ArrayPlot[Table[x + y, {x, 0, nmax}, {y, 0, nmax}], PlotLegends -> True, FrameTicks -> Automatic,

differential equations - How to use DSolve with vectors without decomposing into vector components?

Given a basic, two-dimensional ballistic trajectory problem, I can solve the equations of motion using DSolve (or NDSolve ) by decomposing the vector equations of motion into equations with the scalar components, as follows: DSolve[ Flatten@{ Thread[{rx''[t], ry''[t]} == {rx[t], -9.8 ry[t]}], Thread[{vx[t], vy[t]} == {rx'[t], ry'[t]}], {Thread[{rx[0], ry[0]} == {0, 0}], Thread[{vx[0], vy[0]} == {40 Cos[30 °], 40 Sin[30 °]}]} }, {rx[t], ry[t], vx[t], vy[t]}, t ]; But which general approaches are possible to do this just with "vectors"? (I'm not interested in having anyone solve this particular example per se.) For example, something like this would be desirable: DSolve[ { Thread[m r''[t] == {0, -9.8} r[t]], Thread[v[t] == r'[t]], {Thread[r[0] == {0, 0}], Thread[v[0] == {40 Cos[30 °], 40 Sin[30 °]}]} }, {r[t], v[t]}, t ] Surely this must be possible in some way? I understand that "

linear algebra - Row echelon form question

I am wondering if there is a Mathematica command that will put a matrix in row echelon form. That is, put $$ \begin{bmatrix} 1 & 2 & 3\\ 2 & 3 & 4\\ -1 & 0 & 2 \end{bmatrix} $$ in row echelon form: $$ \begin{bmatrix} 1 & 2 & 3\\ 0 & 1 & 2\\ 0 & 0 & 1\end{bmatrix} $$ I am aware that I can do a sequence of elementary row operations. I am also aware of the RowReduce command which puts a matrix in reduced row echelon form. I even saw a Method->"OneStepRowReduction" used by the RowReduce command which I thought might be the choice. Just wondering if there is a command for this that I cannot find.

data acquisition - Does GeoGraphics support Elliptical Mercator projection?

When working on the answer to this question I found that GeoGraphics seemingly uses by default the Spherical Mercator projection (also known as "Web Mercator") which is used by such geoservices as Google Maps, OpenStreetMap and Wikimapia: EPSG:3857 - WGS 84 / Pseudo-Mercator (Spherical Mercator, Mercator on Sphere) Unlike them such geoservices as Yandex Maps and Kosmosnimki.ru use the Elliptical Mercator projection: EPSG:3395 - WGS 84 / World Mercator (Elliptical Mercator, Mercator on Spheroid) Is it possible to work in the Elliptical Mercator projection with GeoGraphics ? P.S. NGA Advisory Notice on "Web Mercator" . Answer Yes, it is possible to use the ellipsoidal Mercator projection by specifying an ellipsoidal "ReferenceModel" in the projection. To compare, let me define a spherical Mercator projection: In[1]:= webMercator = {"Mercator", "ReferenceModel" -> GeodesyData["ITRF00", "SemimajorAxis"]} Out[

Units, plotting and empty plots

maybe I'm completely newbie but I can't understand the behavior of units and the command plot. I'm doing some easy plotting of the state equation for gasses: R = Quantity[0.0831, ("Bars" "Liters")/("Kelvins" "Moles")]; a = Quantity[3.658, ("Liters")^2]* Quantity[1, ("Bars")/("Moles")^2] b = Quantity[0.0429, ("Liters")/("Moles")] PVW[V_, T_, N_] := ((N*R*T)/(V - N*b)) - (+a*(N^2/V^2)); I then test that units are ok: test = PVW[Quantity[0.6, "Liters"], Quantity[270, "Kelvins"], Quantity[1, "Moles"]]; UnitSimplify[test] And I get my pressure back : Quantity[30.1135, "Bars"] Now I want my plot so I do : Plot[PVW[V, Quantity[330, "Kelvins"], Quantity[1, "Moles"] ], {V, Quantity[0.06, "Liters"] , Quantity[0.6, "Liters"]}, Frame -> True, GridLines -> None, LabelStyle -> {FontFamily -> "Helvetic

graphics - Opacity renders lines incorrect in certain viewing angles

Trying to learn how Opacity works, I found a possible issue. Generating points in a square spiral with: sqrSpiral[rev_, inc_] := Module[{x, y, z, dx, dy, list = {}}, x = y = z = 0; dx = {0, 1, 0, -1}; dy = {1, 0, -1, 0}; Do[ Do[ list = Append[list, {x += dx[[i]], y += dy[[i]], z += inc}], {i, 4} ], {rev}]; list ] and applying it in Graphics like so: pts = sqrSpiral[50, 0.005]; line = Line[pts]; Graphics3D[{Thickness[0.01], Opacity[0.5], Red, line}, Boxed -> False] gives the following strange appearence: As you can see, of all the overlapping lines from the current viewpoint, only the far left corners, seem to be rendered correctly. While turning the spiral as to view it from below, seem to render the lines in a more expected way. Why is this the case? (If you have an answer, please feel free to refine my procedural code:) Answer This appears to be a problem with the hardware rendering engine. A workaround is to use the "BSPTree" renderer: Style[ Gra

sorting - Sort data after specific ordering (ascending/descending) in multiple columns

I have some data: data={{"a", 1, 1}, {"a", 1, 2}, {"a", 1, 3}, {"c", 2, 1}, {"b", 2, 2}, {"b", 2, 3}, {"c", 3, 1}, {"a", 3, 2}, {"a", 3, 3}} When I use: Sort[data] I get the list ordered in incremental order first with column 1 then by 2 and last by the third. Suppose I want the first column in increasing order but the second in decreasing order and the third again in increasing order. How do I do that? I tried with Sort and SortBy but I haven't managed to make it work. The output should be: a 3 2 a 3 3 a 1 1 a 1 2 a 1 3 b 2 2 b 2 3 c 3 1 c 2 1 Answer Caveat lector: Incorrect results are generated by this solution, e.g., sortByColumn[{{"a", 1, 1}, {"b", 2, 3}, {"a", 3, 2}}, {1, 1, -1}] returns {{"a", 1, 1}, {"b", 2, 3}, {"a", 3, 2}} when the correct result is obviously {{"a", 1, 1}, {"a", 3, 2}, {&q

Is the Wolfram | Alpha output in Mathematica not Alpha Pro?

Mathematica 8 includes " Wolfram | Alpha integration", but the features of Alpha available in Mathematica seem not to include many of those available in the "Pro" version of Alpha. Does Mathematica 8 include Alpha's Plus features? If not, has Wolfram announced plans to include them? Answer I can't say that all the Alpha Pro features are available through V8 of Mathematica, but certainly many are. Here are three examples: Type "derivative of x^2" into Alpha. If you are not logged into the Pro version, you will be unable to access the result, other than as a visual image. In particular, you can't easily copy and paste results. Or try, just "z^2-1" in Alpha. You'll notice a number of pods that have an "Enable Interactivity" button. If you press such a button, Alpha generates some type of groovy interactive CDF content, if you are logged into Pro. Without Pro, you can't interact with that content. In Mathematica, all

plotting - Set the scale in ColorFunction

The following plot (A) ListLinePlot[{0,1,2,3},ColorFunction->"TemperatureMap"] goes from blue to read. The following plot (B) ListLinePlot[{4,5,6,7},ColorFunction->"TemperatureMap"] goes also from blue to read. I want the colors to be correlated to the number to be plotted, not the position in the list (as above). Therefore I would like (A) to go from white to yellow (approx.) and (B) from yellow to red (approx.). How can I make the color to be correlated with the value of the number to be plotted and not the position in the list? Answer Your problem is due to the fact, that the default setting is ColorFunctionScaling -> True . You'll have to set ColorFunctionScaling -> False with the downside, that you'll now have to take care of a proper scaling: ListLinePlot[{0, 1, 2, 3}, ColorFunction -> (ColorData["TemperatureMap", #2/7] &), ColorFunctionScaling -> False] ListLinePlot[{4, 5, 6, 7}, ColorFunction -> (ColorData[&quo

customization - Can we make preread replacements in an *.m* file before being run?

This the second question of (152743) , the preamble of which is reproduced here: Those who don't have/prefer the front end of Mathematica will either use a plain ASCII editor to write a script in an .m file or just use Mathematica directly from a command-line terminal. In either case, everything must be supplied in InputForm . When working with a Mathematica package, commonly used symbols/functions might be excessively verbose in InputForm , and certain shortcuts/aliases would be greatly desired. Examples of built-in InputForm shortcuts are the infix operators + ( Plus ), - ( Minus ), ... and . ( Dot ). Two questions that arise as a package developer: (152743) Is there something analogous to #define of C and C++ that can be placed at the top of an .m file that instructs the kernel to make replacements of literal occurrences before the lines are read? (this issue may be easily bypassed if question 1 is answered.) Answer No. In fact, even $PreRead is ignored when reading

logic - Apply Complement to a list of matrices

With a list of defined matrices list={a,b,c,d} How can I apply Complement to obtain Complement[list,{b,c}]=={a,d} Answer I guess your main confusion is that when you do RandomSeed[1234]; list = RandomReal[1, {4, 2, 2}] Complement[list, list[[{2, 3}]]] then the output of the matrices is in the wrong order. The documentation of Complement says The list returned by Complement is sorted into standard order. An easy trick around this is to do the complement on the indices and not on the matrices itself. After that, you can use the indices to access the matrices in list : list[[Complement[Range[Length[list]], {2, 3}]]]

programming - Which Object-oriented paradigm approach to use in Mathematica?

Which Object-Oriented Paradigm (OOP) approach to use in Mathematica for: general implementation, or a particular project? There are a lot of related questions and answers in MSE on doing OOP that concentrate mostly on the "How?" but not on discussing "Why/which OOP approach?" (Or "What are the pre-conditions and consequences of using ...?") Here is a mind-map that shows a way to compare the proposed OOP implementations and styles. (The image links to a PDF that has clickable hyperlinks.) It is probably best the responses of this question to be summarized in a comparison table with columns and rows derived/related to that mind-map. Links Here is a link to a PDF of the mind-map with clickable/linked references also given below. Core concepts of the implementations Objects Pure objects ClasslessObjects, Jakub Kuczmarski, (2014), GitHub , MSE JavaScript style Struct object Associations Rules “The Mathematica Programmer: Object-Oriented Programming”, Maeder

matrix - Product between a column vector and a row vector - error

I know that matrices product is correct when the number of the columns of the first matrix is equal to the number of rows of the second matrix. Why I can't do the product between a column vector and a row vector in Mathematica? For example: $$\begin{bmatrix}1 \\ 2 \\ 3 \end{bmatrix} \, \begin{bmatrix}1 & 2 & 3\end{bmatrix}$$ Mathematica gives me the error: Dot::dotsh: Tensors {{1},{2},{3}} and {1,2,3} have incompatible shapes. Thank you so much.

Subtracting list from list of same dimensions

This might seem like a basic operation I have already searched for similar answers but found none. I want to subtract the second elements of my list ct from the corresponding element in lt, and letting the first element to remain as they are the same. lt={{{1, 1}}, {{2, 1}}, {{3, 1}}, {{2, 3}}, {{5, 1}}, {{2, 4}, {3, 2}}, {{7, 1}}, {{2, 7}}}; ct = {{{1, 1}}, {{2, 1}}, {{3, 1}}, {{2, 2}}, {{5, 1}}, {{2, 1}, {3, 1}}, {{7, 1}}, {{2, 3}}}; as you can see the first elements are the same I want them to remain. desired result nt={{{1, 0}}, {{2, 0}}, {{3, 0}}, {{2, 1}}, {{5, 0}}, {{2, 3}, {3, 1}}, {{7, 0}}, {{2, 4}}}; also note that my resulting list nt is my list lt with the last previous first element. like element 4 in my nt is just my element 2 in lt. and where the second element is 0 that means there is no previous first element of the same value, that is a next way to look at it. Answer You can do: lt[[;; , ;; , 2]] -= ct[[;; , ;; , 2]]; lt {{{1, 0}}, {{2, 0}}, {{3, 0}}, {{2, 1}}, {{5,

differential equations - Two-dimensional catenary in Mathematica

I'm working in Mathematica to plot a 2-d catenary in Euclidean space according to this Math Stack Exchange Link , specified with a square Dirichlet boundary condition. Here's what I've coded using Mathematica , followed by an error I receive. My goal was to set the surface integral to 1.5 because it's gotta be at least 1 if it's a sagging surface pinned at edges on a $1\times 1$ square. NDSolve[ { (-(D[u[x,y],x,x]+D[u[x,y],y,y])*(u[x,y]+λ)) == 1 , Integrate[ ( 1+D[u[x,y],x]+D[u[x,y],y] )^(1/2) ∈ RectangularPolygon[4],x,y]==1.5 , DirichletCondition[u[x, y] == 0, True] } , u , {x, y} ∈ RegularPolygon[4] ] NDSolve: There are fewer dependent variables, {u[x,y]}, than equations, so the system is overdetermined I think this is conditionally stable, so I've worked to provide a fair approximation of a stable error. If I omit the surface integral line, I'm told that NDSolve doesn't deal with non-linear coefficients. I was told elsewhere that thi

import - How to manipulate web pages on Mathematica?

I wanted to input some data on this page through Mathematica . Then I would press the "buscar" button also through Mathematica coding and get the results on Mathematica . The most similar post I've found was this one . I'm trying to import through the Import[] function: Import["http://www.fundamentus.com.br/buscaavancada.php", "Data"] When I do that, it shows this: {{{{"Página inicial", "Investimento consciente", "Entre em contato"}, {"Detalhes", {"Balanço patrimonial", "Demonstrativos de resultados", "Indicadores fundamentalistas"}, {"Balanços em Excel", "Proventos"}, "Histórico de cotações"}}, {{"Preencha apenas os campos que serão \ usados na pesquisa", "Use . (ponto) como separador decimal", "Utilize o formato decimal para representar porcentagens. Ex: \ Para 15% digite 0.15"}, {{"? P/L (Preço sobre lucro)