Skip to main content

Posts

Showing posts from May, 2016

equation solving - Solve[Tan[theta] == (b*Sin[t])/(a*Cos[t]), theta] breaks when "Reals" is added?

Mathematica solves this equation fine: Solve[ Tan[theta] == (b*Sin[t])/(a*Cos[t]), theta] // InputForm {{theta -> ConditionalExpression[ArcTan[(b*Tan[t])/a] + Pi*C[1], Element[C[1], Integers]]}} The solution is real when $a$, $b$, and $t$ are real (and $t$ isn't a multiple of $\frac{\pi}{2}$). However, adding the Reals condition breaks things: Solve[ Tan[theta] == (b*Sin[t])/(a*Cos[t]), theta, Reals] // InputForm Solve::nsmet: This system cannot be solved with the methods available to Solve. Solve[Tan[theta] == (b*Tan[t])/a, theta, Reals] Why? Answer The issue we encounter here is an apparent incompleteness of the recent updates in the system, we should remember that Solve has been updated in the recent versions of Mathematica and although documentation pages say "last modified in 8 ", one can distinguish various different issues between ver.8 and ver.9 , it's just a state of art. In ver. 8 we get: Solve[ Tan[θ] == b Sin[t]/(a Cos[t]), θ] Solve...

machine learning - Options for ValidationSet accuracy from NetTrain?

With NetTrain[] if you use the option ValidationSet->Scale[.1] it will run a validation test on 10% of the training data after each epoch. For example, data = RandomSample@Table[x -> Exp[-x^2] + RandomVariate[NormalDistribution[0, .15]], {x, -3, 3, .2}]; net = NetChain[{150, Tanh, 150, Tanh, 1}, "Input" -> "Scalar", "Output" -> "Scalar"]; trained = NetTrain[net, data, ValidationSet -> Scaled[.1]]; My question is how to get more information on the validation tests performed , i.e. what was the set (indices of examples) and what were the metrics (precision, recall, ...). And are there any (undocumented) suboptions that can control the splits/shuffling choices for each validation test performed? Follow-up: is there any mechanism for breaking out of the training loop if the validation results start to plateau? Answer I'll add to our ToDo list the idea of having the validation indices be available as a property of NetTrain.

graphics - Adapt ticks in plot and font in legend

Some of my 2-dimensional data are displayed with a code similar to this: Needs["PlotLegends`"] sampleData = Transpose[{RandomVariate[NormalDistribution[0, 3*10^-6], 20000], RandomVariate [NormalDistribution[0, 3*10^-6], 20000]}]; binning = {{-1*10^-5, 1*10^-5, 1*10^-7}, {-1*10^-5, 1*10^-5,1*10^-7}}; (*binning of my sampleData*) maxBinnedData=Max[HistogramList[sampleData,binning][[2]]]; (*seachring for the maximum of the binned data*) ShowLegend[DensityHistogram[sampleData,binning,LabelingFunction->None, PerformanceGoal->"Speed", ColorFunction->(If[1-#1===0,White,ColorData["Rainbow"][#1]]&), ColorFunctionScaling->True,PlotRange->{{-1*10^-5, 1*10^-5},{-1*10^-5, 1*10^-5}}, FrameLabel->{"x", "y"}, LabelStyle->Directive[Black,FontSize->12,FontFamily->"Arial"],ImageSize->{500,500}],{(If[1-#1===0,White,ColorData["Rainbow"][1-#1]]&),11, ToString[maxBinnedData],ToString[0],LegendTextOffse...

calculus and analysis - On the n-th derivative of the inverse function

Given a function $f(x)$ , its inverse $g(x)$ is defined as $g(f(x)) \equiv x$ . In light of this, the n-th derivative of $g(x)$ can be recursively calculated as follows: list = {}; For[n = 1, n eqn = D[g[f[x]], {x, n}] == D[x, {x, n}]; var = Derivative[n][g][f[x]]; If[n == 1, list = Join[list, Solve[eqn, var][[1]]], list = Join[list, (Solve[eqn, var] /. list)[[1]]] ] ] list // Expand // TableForm In MMA you can get this very simply by writing something like this: Derivative[n][InverseFunction[f]][f[x]] The question that arises is the following : is the latter formulation using a recursive process like the one shown above or is there a non-recursive formulation? Answer D[InverseFunction[f][x], {x, 6}] Towards the question whether this is computed recursively: I guess so from analyzing the Trace produced by executing the code: Table[ Length@Trace[ D[InverseFunction[f][x], {x, k}] ], {k, 1, 12}] {6, 7, 7, 10, 13, 18, 25, 36, 51, 73, 103, 145...

complex - ComplexExpand and Arg function

Why does the command ComplexExpand[Arg[a]] gives Arg[a] instead of 0? Isn't it that ComplexExpand supposed to assume all unspecified variable to be real, and the argument of real variable is 0? Answer The function ComplexExpand itself does not know what is a , complex, real and so on. One needs to instruct Mma about it. For example, Simplify[ComplexExpand[Arg[a]], a > 0] (* 0 *) Here is another example: Simplify[ComplexExpand[Arg[a]], a (* \[Pi] *) On the other hand, if one does not fix the sign of a, but only that it is Real, Mma assumes that it can have the both signs and leaves the both possibilities: Simplify[ComplexExpand[Arg[a]], a \[Element] Reals] (* Arg[a] *) Even more this is valid, if a may be complex: Simplify[ComplexExpand[Arg[a]]] (* Arg[a] *) Have fun!

VertexLabels with Graph Properties

Suppose I have a graph like this Graph[ {1 2, 2 3, Labeled[3 1, "hello"]}, VertexLabels -> Placed["Name",StatusArea] ] Now I want to add more properties to all the nodes. For instance, I want to replace name of node 1 by number 3700, node 2 by 3701, node3 by 3703 and those should be displayed only in the status area. Along with replacing the node names, I also want some more properties associated with nodes. For instance, I'd like 3700, "h1" to be displayed in the status area when I place my mouse pointer at node 1; at node 2, it should display 3700, "h2" etc. (not exactly those but some other display stuff). How can I do it?

import - Stream CSV or TSV files

RAM limitations make import impractical for large CSV files. Is it possible to Stream CSV correctly? str = OpenRead["EU.csv"]; Read[str, "CSV"] Read::readn: Invalid real number found when reading from EU.csv Read@str Read::readt: Invalid input found when reading "lTid, cDealable, CurrencyPair, RateDateTime, RateBid, RateAsk" from EU.csv Close@str Here's the CSV file. Though I think it's properly formatted. Answer Here is a function which may help: Clear[readRows]; readRows[stream_, n_] := With[{str = ReadList[stream, "String", n]}, ImportString[StringJoin[Riffle[str, "\n"]], "Table"] /; str =!= {}]; readRows[__] := $Failed; I tested on your file and it works all right (it may make sense to read rows in batches, this is much faster): n=0; str = OpenRead["C:\\Temp\\EUR_USD_Week1.csv"]; While[readRows[str, 1000] =!= $Failed, n++]; Close[str]; n (* 82 *) By the way, speaking of practicality of Impo...

files and directories - What is the difference between a .wl package and a .m package?

In Mathematica 10.x, one now has both .wl Wolfram Language Packages and .m Wolfram Mathematica Packages. What's the difference? Is one of the two formats to be preferred in certain situations and, if so, which one and where? Why, after making the menu selection File > New > Package , entering code, and saving, is it offered as default to save in the .wl format? I have read the discussion here , but failed to see there satisfactory answers to those questions. Note: I don't find any listing of Wolfram Language Package here .

bugs - Reading a HDF file im Mathematica

Bug introduced in 8.0 or earlier and persisting though 10.2 On OS X, the problem is present in 9.0 but not in 10.0, 10.1 or 10.2. I am trying to read a HDF file in Mathematica 9 on OS X and get this message: LinkObject::linkd: "Unable to communicate with closed link LinkObject[!(\"/Applications/Mathematica.app/SystemFiles/Converters/Binaries/MacOSX-x86-64/HDF.exe\", 247, 4)]." Any clue what is going on ??? The command was: Import["CAL_LID_L2_05kmALay-Prov-V3-02.2013-01-02T16-42-52ZD_Subset.hdf",{"Datasets", "Number_Layers_Found"}] The file can be downloaded from http://ge.tt/3eSkGUM2/v/0?c

linear algebra - Efficiently Constructing Rank One Approximations for a Matrix using SVD

Suppose I have a $m\times n$ matrix $A$ (real for simplicity). Then SingularValueDecomposition[A] yields 3 matrices $U$, $\Sigma$ and $V$ such that $A = U\Sigma V^\top = u_1 \sigma_1 v_1^\top + u_2 \sigma_2 v_2^\top + \cdots$, where $U = [u_1\;\; u_2 \ldots]$ (vector = column matrix). Successive approximations for $A$ are given by the rank 1 matrices $u_1 \sigma_1 v_1^\top$, etc. I wanted to make a function to compute this but found myself doing all sorts of messy manipulations due to Mathematica's matrix structure (and/or my lack of knowledge on how to use them). Here is my tentative function. It has as input any matrix A and an optional argument n saying how many rank 1 matrices should be summed. This function is not meant to be numerically fast or anything; perhaps I would use it as a educational tool to examine different approximations of A or etc. The point is in the Sum function where I would like to know: is there a more efficient (or perhaps cleaner) way of doing the matr...

Dynamic does not update when wrapped in DynamicModule

I'm trying to wrap some dynamic code into DynamicModule to localize all the variables, yet when I do that, the variables stop updating. That does not happen if I use Module instead. However, the variables get highlighted in red and when I hover over them with the mouse pointer the following message pops up: "A variable was used where it is probably not going to be evaluated before going out of scope". The code in question is from Pickett's answer to my earlier question ( AJAX-style HTTP calls triggered by a variable change ): url = "https://maps.googleapis.com/maps/api/geocode/json"; callback[_, "data", data_] := choices = extractsAddresses@First@FromCharacterCode[data] Needs["GeneralUtilities`"] extractsAddresses[data_] := ToAssociations[ImportString[data, "JSON"]][["results", All, "formatted_address"]] fetchChoices[addr_] := URLFetchAsynchronous[ url, callback, "Parameters" -> {"ad...

machine learning - What is the error in this example of training a SVM model

data = RandomReal[{0, 35}, {400, 200}]; trset = Association[{"class1" -> data[[1 ;; 100]], "class2" -> data[[101 ;; 200]]}]; valset = Association[{"class1" -> data[[201 ;; 250]], "class2" -> data[[201 ;; 250]]}]; Classify[trset, ValidationSet -> valset, Method -> "SupportVectorMachine"] I get this error: "Part::partd: Part specification 0.[[1]] is longer than depth of object. >> Part::partd: Part specification 0.[[2,1]] is longer than depth of object. >>" Here this example with MNIST dataset work correctly,!?! totalSet = ExampleData[{"MachineLearning", "MNIST"}, "Data"]; {trainingSet, validationSet,testSet} = {#[[;; 400]], #[[401 ;; 550]], #[[551 ;; 700]]} &RandomSample[totalSet]]; c = Classify[trainingSet, ValidationSet -> validationSet, Method ->"SupportVectorMachine"];

bugs - Why does one of my Manipulate integer variables get turned into a real?

Bug introduced in 9.0 or earlier and persisting through 11.0.1 or later I'm developing code for manipulating graphs. Spot the difference in the 2 Manipulates below: Manipulate[ {n, m}, {{n, 10, "no of vertices"}, 1, 18, 1}, {{m, n, "number of edges"}, n, n (n - 1)/2 , 1} (* using the +/-/slider for the number of edges does not generate Reals but only Integers as expected *)] this first example works as expected but Manipulate[ {n, m}, {{n, 10, "no of vertices"}, 1, 18, 1}, {{m, n, "number of edges"}, n - 1, n (n - 1) /2, 1} (* using the +/-/slider for the number of edges now generates Reals not Integers: what gives? *)] turns my nice integers into reals as soon as I change the number of edges. I can turn this back into an integer when that's what I need, but I'd prefer not to. Naturally I have a more complex task to complete but these examples are simple enough to illustrate the issue. Version: Mathematica 9.0.1.0 Plat...

Fundamental Theorem of Calculus for definite integrals... assume continuity?

So here's the problem: I can evaluate the indefinite integral: Integrate[D[u[x], x], x] u[x] However, I'd like to evaluate: Integrate[D[u[x],x], {x, x0, x1}] and get u[x1] - u[x0] Or especially, evaluate Integrate[D[u[x, y], x], {x, x0, x1}] and get u[x1, y] - u[x0, y] Is there a way that I can assume that D[u[x], x] is continuous in the range x0 to x1? Is there a some assumption that can be met in order for me to evaluate the fundamental theorem of calculus?

kernel - Autoload a package

I want to aoutoload a package at the beginning of a notebook. I set up my directory as written here How to use the Autoload directory? So, I have these files: ../Work/MyFile.nb ../Work/Autoload/MyPack/MyPack.m ../Work/Autoload/MyPack/Kernel/init.m. MyPack.m : ClearAll["Progetto`*"]; BeginPackage[ "Progetto`"] Prova::usage="Prova[]" Begin["`Private`"]; Prova[]:=5+1; End[] EndPackage[] init.m : Get["MyPack`MyPack`"] In MyFile.nb, I would like use Prova[] , but the output isn't 6 but is Prova[] . Where am I wrong? Am I missing something in init.m ? Answer I want to aoutoload a package at the beginning of a notebook . In this case, create an initialization cell in the notebook, and load that package in that cell. Select the cell, and tick Cell menu -> Cell Properties -> Initialization Cell. "Autoloading" refers to loading something on kernel startup, and is completely independent of notebooks. ...

programming - How to find first list element that differs from average of N previous elements by more than a given amount?

Given a list of real numbers, I need to write a function that returns the value of the first element in the list that differs from the mean of the previous $N$ elements by greater than $P$ standard deviations of those same elements. (I use mean and standard deviation as sample functions, I may decide to use something else.) Clearly, I can write a loop to do this, but I'd like to use functional programming techniques to do this, and continue to learn better Mathematica programming style. Select[ ] looked promising, but I see no way to involve the previous list elements in the selection criterion. Thanks in advance for your help! Tom Answer Here's an attempt (without select) lst = {1, 2, 2, 1, 2, 5, 2, 4}; n = 4; p = 1; Flatten[If[Abs[Take[#, -1] - Mean[Drop[#, -1]]][[1]] > p *StandardDeviation[Drop[#, -1]], Take[#, -1], {}] & /@ Partition[lst, n + 1, 1, 1]] // First Alternatively with Select. Select[Partition[lst, n + 1, 1, 1], Abs[Take[#, -1] - Mean[Drop[#, -1]]]...

front end - How can I get the box size of a BoxObject?

I've often wanted to set the size of an interface element to something like Full - 50 , so as to not over-constrain box sizes. One approach to this would be to simply use a Dynamic[boxsize - 50] as my ImageSize . Unfortunately, for boxes that information isn't possible to extract by normal means. I've always resorted to hacks and workarounds, but I don't see what that info shouldn't be possible to extract from the FE. In digging I found FrontEnd`GetBoundingBoxSizePacket , but it always returns one of two things. Either it gives: FrontEndExecute[FrontEnd`GetBoundingBoxSizePacket@EvaluationCell[]] {{34., 13., 7.}} Or FrontEndExecute[FrontEnd`GetBoundingBoxSizePacket@1] $Failed No matter what FE object I pass to it, it only ever returns one size. Does anyone know can I get the size of a BoxObject ?

dynamic - How to interactively transform an image (rotate / translate / etc) on a per-component basis?

I have binary images like this one and I want to be able to interactively select its components and rotate them around its centroid by a different angle for each component. I may also want to apply different Image transformations such as translations, dilations, etc., always on a per-component basis Please keep in mind that the original component partition should be preserved, so if as a result of a given transformation two or more components get merged, they should still be considered as different components for the next transformation.

plotting - Preparing 2d plots for publication

When it comes to plotting a data my general attitude is to avoid post processing (say with adobe illustrator) as much as possible. To follow this strategy I would like to prepare publication-ready pdf plots with Mathematica . Here are my requirements Plotted lines should have width of exactly 1pt . The same should be true for the lines forming axes, frames, ticks. The ticks have a commensurate length. I find it is optically pleasing to have major ticks of 4pt lengths. The graph should have a dimension of one column, i.e. ~ 8.5cm or 240pt. All the tick labels, axes labels, etc. should be done with 12pt Helvetica . No white background. One can argue about the art value of this setup. I, personally, find it is a good compromise between the visibility and simplicity. I remember these numbers and keep them the same across different programs and publications. I tried to develop very easy solution that can be kept in mind. Since there is a known problem with tick length (it cannon be set e...

graphs and networks - Bug in NearestNeighborGraph

Update Not fixed in 12.0. NearestNeighborGraph generates incorrectly formatted output on rasterized input. Reported to Wolfram support CASE:4093797 $Version (* "11.3.0 for Mac OS X x86 (64-bit) (March 7, 2018)" *) NearestNeighborGraph[ Rasterize[Style[#, 20], "Image"] & /@ Alphabet[], 2, VertexLabels -> "Name" ] The labels are too large. Is there a workaround? Answer Assuming you are asking for a workaround, you can generate the output you expect with: v = Style[#,20]& /@ Alphabet[]; rv = Rasterize/@v; NearestNeighborGraph[ rv, 2, VertexLabels->Thread@Rule[rv,v] ]

graphics - Why is Text in an Image cut off?

I want to create a long, skinny Image containing only text. This makes a square image of the default size. Image@Graphics[ { FontSize->20, Text["now is the time for all good men to come to the aid of their country"] } ] So I prescribe the dimensions I want: Image@Graphics[ { FontSize->20, Text["now is the time for all good men to come to the aid of their country"] }, ImageSize->{1000,30} ] and the result is cropped well inside the ImageSize so some of the text is missing. But the Graphics alone is appearing correctly. Graphics[ { FontSize->20, Text["now is the time for all good men to come to the aid of their country"] }, ImageSize->{1000,30} ] Why does Image mysteriously crop the input? Answer Image defaults to a certain size, but can be adjusted with its own ImageSize . g=Graphics[{FontSize -> 20, Text["now is the time for all good men to come to the aid of their country"]}; Image[g, ImageSize -> ...

bugs - Wolfram CDF Player not working anymore in WordPress v.4.0.1

I usually instert my CDF demonstrations in my WordPress site with the WolframCDF plugin v.2.1. It worked fine till a couple of days ago. But, after the recent (automatic) upgrade of WordPress from 4.0.0 to 4.0.1 that doesn't work anymore. The CDF is no more shown in the page, just the html code calling it. Is anyone else experiencing this problem? I'm afraid I'll have to downgrade to WordPress 4.0.0 (not so easy) or wait for the developer of the WolframCDF plugin to adjust it to the new version of WP. At the moment my website ( www.lucamoroni.it ) heavily based on CDF simulations is totally useless! But maybe there could be some workaround (i.e. modify manually some configuration file) to fix things (at least temporarily). Any help? (any dirty trick?) Answer Update The new plugin Mathematica Toolbox can embed CDFs and do many other things. The official plugin is still not working. The problem is that whoever wrote the Wordpress plugin didn't use the official API to p...

plotting - Same Colors to Match Two Contour Plots

I have two contour plots: c1 = ContourPlot[Cos[x] + Cos[y], {x, 0, 4 Pi}, {y, 0, 4 Pi}, FrameTicks -> None] c2 = ContourPlot[10*Cos[x] + Cos[y], {x, 0, 4 Pi}, {y, 0, 4 Pi}, FrameTicks -> None] I want to be able to compare them not only in terms of numbers but also in terms of colors. So same value -> same color. How can I make sure that the colors between the two contour plots match ? Also, they should have one unique legend. Answer Find the narrowest range that covers the range of both plots and use it as color function range in both plots: range = MapThread[# @ #2 &, {{Min, Max}, Transpose @ (Through[{MinValue, MaxValue}[{#, 0 {Cos[x] + Cos[y], 10 Cos[x] + Cos[y]})}] {c1, c2} = ContourPlot[#, {x, 0, 4 Pi}, {y, 0, 4 Pi}, FrameTicks -> None, PlotLegends -> Automatic,ImageSize -> 300, ColorFunction -> ColorData[{"Rainbow", range}], ColorFunctionScaling -> False] & /@ {Cos[x] + Cos[y], 10 Cos[x] + Cos[y]}; Row[{c1, c2}] To use t...

export - How to extract all images from avi when FrameRate is not Integer

Here is an avi movie (204*432 Pixels) which contains 22 different images with numbers from 1 to 22. I tested e.g. with VirtualDub and MATLAB that all extracted images are different. Movie: https://drive.google.com/open?id=0B9wKP6yNcpyfUE1hb0UyNXhDRFk (5.5MB) When I extract the images with the mathematica code below image 20 is same as image 19. All the rest is correct. The two same images are seen here: Import[avifile, {"AVI", "ImageList", Range[19, 20, 1]}] The error occurs due to the non integer FrameRate : Import[avifile, {"FrameRate"}] 15.7143 VirtualDub and other software do not care about the frame rate. They simply extract sequentially image by image and the result is corrrect: {Import["virtualdub_000019.png"], Import["virtualdub_000020.png"]} Do you know a solution for mathematica? My code for extracting grayscale images is: avifile = "20170623_movie_for_testing_duplicate_images.avi"; numberImages = Length@Import[avi...

differential equations - Finding the eigenfunctions of one and two dimensional Harmonic Oscillator

(Edited) For finding the ground state wave function of: $ H\psi(x) = (-1/2)d^2\psi(x)/dx^2 + (1/2)x^2\psi(x) = E \psi(x)$ I have written: mOneDSchEq[n_] := Table[Switch[i - j, -1, p[x[i]], 0, (10/(n + 1))^2 q[x[i]] - 2 p[x[i]], 1, p[x[i]], _, 0], {i, n}, {j, n}]; q[x_] := -x^2; p[x_] := 1; Xarray[n_] := Do[x[i] = -5 + i 10/(n + 1), {i, 0, n + 1}]; EigVec[n_] := Eigenvectors[mOneDSchEq[n]]; lisEigVec = EigVec[35]; OneEigVec[j_] := Part[Reverse[lisEigVec], j]; y[i_] := Part[OneEigVec[1], i]; listOfPoints = Join[{{x[0], 0}}, Table[{x[i], y[i]}, {i, 1, 35}], {{x[36], 0}}]; ListPlot[listOfPoints, PlotJoined -> True, PlotRange -> All, PlotLabel -> "Ground State Wave Function of Harmonic Oscillator", AxesLabel -> {"x", "y"}] Which I have obtained the Gaussian, correctly. The question that came to my mind is that: Is it possible by knowing the ground stat eigenvalue, i.e. 1/2, solving the Schrödinger equation numerically, and obtain the ground state wa...

How to deal with the condition $u_i=u_{i+1}$ in B-Spline basis function?

The defintion of B-Spline basis function as shown below: Let $\vec{U}=\{u_0,u_1,\ldots,u_m\}$ a nondecreasing sequence of real numbers,i.e, $u_i\leq u_{i+1}\quad i=0,1,2\ldots m-1$ $$N_{i,0}(u)= \begin{cases} 1 & u_i\leq u Although I know that Mathematica owns a built-in function BSplineBasis , however, I would like to write my auxiliay function $N_{i,p}(u)$ to learn the NURBS theory and Mathematica programming . NBSpline Alogrithm: (*=======================Caculate N[i,0](u)================================*) NBSpline[i_Integer, 0, u_Symbol, U : {Sequence[_] ..}] /; i Piecewise[ {{1, U[[i + 1]] {0, u = U[[i + 2]]}}] (*=======================Caculate N[i,p](u)================================*) NBSpline[i_Integer, p_Integer, u_Symbol, U : {Sequence[_] ..}?OrderedQ] /; p > 0 && i + p Module[{ini}, ini = Table[NBSpline[j, 0, u, U], {j, i, i + p}]; First@Simplify@ Nest[ Dot @@@ (Thread@ {Partition[#, 2, 1], With[{m = i...

front end - How to make InputField admit multiple entries

Is there a way to make InputField[] compatible with RepeatingElement or a similar scheme of user interaction? The idea is to create an interface with many user defined variables, as many as the user sees fit to be exact. Answer Here's something to start with: multiInput // ClearAll multiInput[Dynamic[list_], type_: Number, def_: 0, opts___] := DynamicModule[{n = Length[list]}, Column[{ Button["+", AppendTo[list, def]; n++;], Dynamic[ Grid[ Table[{ InputField[Dynamic[list[[#]]], type, opts], Button["-", n--; list = Delete[list, #]] } &@i, {i, n}] , Alignment -> {Left, Center}], TrackedSymbols :> {n} ] }, BaseStyle -> ButtonBoxOptions -> {ImageSize -> All, FrameMargins -> 5, ContentPadding -> False}] ] l = {}; multiInput[Dynamic@l] Dynamic@l

Optimising coefficient finding functions

I'm seeking a generalisation to this question , where I am looking to list the coefficients (without repetition) to monomials of the form $$(x_{1}^{3}+x_{2}^{3}+x_{3}^{3}+x_{4}^{3})^4\cdot(x_{1}^{2}+x_{2}^{2}+x_{3}^{2}+x_{4}^{2})\cdot(x_{1}+x_{2}+x_{3}+x_{4})^{2}$$ for example. Motivation: I am currently using the following functions: ip[n_] := Times @@@ Flatten[Table[{Table[Prime@ k, {k, Length[IntegerPartitions[n][[s]]]}]}^{IntegerPartitions[n][[s]]}, {s, Length[IntegerPartitions[n]]}], 1] alpha1[omega_] := Join[{a^omega}, Times @@ # & /@ Rest@(List @@ # & /@ (If[# == 1, 1, If[PrimePowerQ[#] == True, Power @@ {a, FactorInteger[#][[1, 2]]}, (Power @@@Transpose@{Take[ToExpression[CharacterRange["a", "z"]], Length@FactorInteger@#], (Reverse@Sort@FactorInteger[#][[All, 2]])})]] & /@ip@omega))] timesABC[omega_] := Module[{ aa = Flatten[#] & /@ (DeleteDuplicates[#] & /@ Part[#] & /@ (Split[#] & /@ (Reverse@Flatten[#] & /@ (Split[#]...

graphics3d - Trouble with discrete MeshRegions: Integrating over plane slices

I would like to slice a discrete 3D region with a plane, and integrate some field over the resulting 2D region (embedded in 3D). Let me be clear: I do not mean analytical regions (the kind you could define via ImplicitRegion), but specifically discrete regions, as in my project I am importing those from experimental data. There are two strategies I have tried. Here is a quick summary: Strategy 1 is to use SliceContourPlot3D with RegionFunction to obtain a 2D region (i.e. surface) embedded in 3D. The problem is that the mesh is faulty and has no boundary, so I cannot e.g. compute fluxes through it. Any suggestions fixing this are more than welcome. Strategy 2 is to transform the problem to in-plane coordinates (i.e. make it a genuine 2D problem) and use the standard two-dimensional RegionPlot . This works . The drawback is that the mesh is purely 2D (no longer embedded in 3D), so I cannot superimpose the result with the original geometry, which is important to me. If there is a nic...

graphs and networks - Vertex sizes scaled by vertex degree?

Is there any way of scaling the sizes of the vertices of a network proportional to the vertex-degrees of the vertices in Mathematica? Thanks. Answer SeedRandom[5] g = RandomGraph[{6, 10}] vd = Thread[VertexList@g -> Normalize[VertexDegree@g, Total]]; g2 = SetProperty[g, VertexSize -> vd]

symbolic - Telling mathematica to output * instead of space for multiplication, so I can copy as plain text

I am trying to get some symbolic expressions in Mathematica which I would like to paste into my C/MATLAB codes. This can be accomplished nicely by selecting the expression and right-clicking to select Copy as plain-text . However there is one small issue I have. Consider the simplest possible case for 2 symbols a and b In[1]:= c = a*b Out[1]= a b How can I tell Mathematica to produce all its output as a*b and not a b Without this, I have to go through the pain of replacing manually all spaces in my C/MATLAB codes with the * espcecially for long expressions. Answer The * multiplication operator is rendered in InputForm : c = a b; c // InputForm a*b For producing/exporting strings: ExportString[c, "Text"] ToString[c, InputForm] "a*b" "a*b"

differential equations - Mismatch between Mathematica and COMSOL in 3D FEM problem

I would like to solve an advection-diffusion problem on a torus domain. There are three Dirichlet conditions: One at the inlet (concentration $c=0$ ), one at the outlet ( $c=0.5$ ) and one at the wall ( $c=1$ ). The geometry is set up in the following code. Note that RegionCapillary is the full solution domain, RegionCapillary2D is a 2D projection for convenient plotting and the list points goes through the centre of the tube. In the plot below RegionCapillary is orange and RegionCapillary2D is blue. radiusMajor = 4; radiusMinor = 1; RegionCapillary = ImplicitRegion[( radiusMajor - Sqrt[x^2 + y^2])^2 + z^2 radiusMinor^2 && x >= 0, {x, y, z}]; RegionCapillary2D = ImplicitRegion[( radiusMajor - Sqrt[x^2 + y^2])^2 x >= 0, {x, y}]; RP = RegionPlot3D[ DiscretizeRegion /@ {RegionCapillary, RegionCapillary2D} // Evaluate, Axes -> True, AxesLabel -> {x, y, z}, PlotStyle -> {Opacity[0.4], Opacity[1]}]; LP = ListPointPlot3D[ points = Rev...