Hot answers tagged

53

2014-04-12 NOTICE: MATLAB R2014a contains a bug that breaks MATLink on OS X and Linux (Windows is fine). If you use MATLink on OS X or Linux, please consider keeping MATLAB R2013b until R2014b comes out. Due to the nature of the problem there is no quick workaround that we could apply in MATLink. For full compatibility with Mathematica 10, please upgrade ...


32

There is the ToMatlab package that will convert Mathematica expressions to MATLAB equivalents. For example: <<ToMatlab` Expand[(x + Log@y)^5] // ToMatlab (* x.^5+5.*x.^4.*log(y)+10.*x.^3.*log(y).^2+10.*x.^2.*log(y).^3+5.* ... x.*log(y).^4+log(y).^5; *) It even conveniently breaks it using ... and can also convert matrices: RandomInteger[5, ...


22

There was an update for Array, not done to the end. The method below does not work for earlier versions even though that Array is New in 1 | Last modified in 4 Moreover WRI forgot to update docs for error messages: Array::plen - the first example gives no error in V9. V9 Array[# &, n, {start, stop}] Array[# &, 10, {-1, 1}] {-1, ...


20

Here's a somewhat simpler way: logspace[a_, b_, n_] := 10.0^Range[a, b, (b - a)/(n - 1)] This gives a sequence starting at 10^a and ending at 10^b, with n points logarithmically spaced, as does MATLAB's logspace() function.


17

Based on the MATLAB documentation, it would appear that this is accomplished by simple zero-filling. As such, you can obtain the same result in Mathematica using Fourier[PadRight[list, n, 0.], FourierParameters -> {1, -1}] where list is your signal and n is the desired length. For a multidimensional FFT, replace n with {n1, n2, ...}, where n1, n2, ...


17

Matlab tends to be data oriented (and it is very good at that). You can do some symbolic manipulation but it is not smooth and easy. I used Matlab to analyze NMR data. I built hundreds of matlab scripts to facilitate the procedure. You can do the same thing with Mathematica using Packages but the learning curve is a bit steeper. Mathematica's symbolic ...


16

According to the Mathematica documentation on this page: Here is how to define a 5(4) pair of Dormand and Prince coefficients [DP80]. This is currently the method used by ode45 in MATLAB. DOPRIamat = { {1/5}, {3/40, 9/40}, {44/45, -56/15, 32/9}, {19372/6561, -25360/2187, 64448/6561, -212/729}, {9017/3168, -355/33, 46732/5247, 49/176, ...


14

You miss that many Mathematica functions are listable. It allows you to write a fast and clear code init2[distance_] := uniMass Total[liuQuartic[distance, h] UnitStep[2 h - distance], {2}] h = 0.1; uniMass = 1.0; liuQuartic[d_, h_] := d^2 - h^2; totalPos = RandomReal[1, {1119, 2}]; res1 = initializeDensity@computeDistance[totalPos]; // AbsoluteTiming res2 ...


14

As suggested by @Jens, HDF5 can be fast imported and manipulated in Mathematica. The performance of importing HDF5 is as efficient as MAT file in Python and you can read only a part of HDF5 file into memory. From the question, Mathematica is about 3~4 times slower in reading MAT files. The speed of reading HDF5 files are very close to the speed in Python. ...


13

Blend gives smooth transition between a list of colors: cf[v_] := Blend[{Black, Red, Yellow, White}, v] DensityPlot[Exp[-x^2 - y^2], {x, -2, 2}, {y, -2, 2}, ColorFunction -> cf, PlotPoints -> 300] For a clear distinction between some set of contours you can use ContourPlot: ContourPlot[Exp[-x^2 - y^2], {x, -2, 2}, {y, -2, 2}, ColorFunction -> ...


13

My take: toward[p1_, p2_, v_: .05] := p1 + v Normalize[p2 - p1]; {n, r} = {4, 3}; DynamicModule[{pts, history}, pts = r {Cos[#], Sin[#]} & /@ Range[2 Pi/n, 2 Pi, 2 Pi/n]; history = {pts}; Print[Dynamic[ListPlot[Transpose@history, AspectRatio -> Automatic, Joined -> True, PlotStyle -> Directive[Thick, CapForm["Round"]], ...


13

Modify the calculation order a little to avoid ragged array and then make use of Listable and Compile: computeDistance[pos_] := DistanceMatrix[pos, DistanceFunction -> EuclideanDistance] liuQuartic = {r, h} \[Function] 15/(7 Pi*h^2) (2/3 - (9 r^2)/(8 h^2) + (19 r^3)/(24 h^3) - (5 r^4)/(32 h^4)); initializeDensity = With[{l = liuQuartic, m = ...


12

(Update, added more points, and more timings) Using MATLAB's help standard example for meshgrid: Mathematica implementation meshgrid[x_List, y_List]:={ConstantArray[x,Length[x]],Transpose@ConstantArray[y,Length[y]]} {xx, yy} = meshgrid[Range[-2, 2, .1], Range[-4, 4, .2]]; c = xx*Exp[-xx^2 - yy^2]; pts = Flatten[{xx, yy, c}, {2, 3}]; ListPlot3D[pts, ...


12

Here I show the basic way to call MATLAB using NETLink under Windows via the MATLAB COM interface. This answer is Community Wiki, feel free to extend it to others platforms and/or improve it! In[1]:= Needs["NETLink`"] matlab = CreateCOMObject["matlab.application"] Out[2]= «NETObject[COMInterface[MLApp.DIMLApp]]» Now one can invoke MATLAB functions: ...


12

It's hard to know quite where to start with this, but I'd start with the answers to this question for some initial guidance. As a general guide, nested For loops are almost never necessary and using list-based operations is much more efficient, as well as readable and less prone to error. Let's take the inner loop first. For[h = 1, h <= 3, h = h + ...


11

You could try something like the following. bounded[Indeterminate] := $MaxMachineNumber; bounded[x_?NumericQ] := x This gives a very large number instead of Indeterminate so NMinimize keeps searching. NMinimize[bounded[J[{θ0, θ1, θ2}, X1, y1]], {θ0, θ1, θ2}] (* {0.203498, {θ0 -> -25.1613, θ1 -> 0.206231, θ2 -> 0.201471}} *) Incidentally, ...


10

Some theory This is not completely trivial, and the reason is in the differences between how Matlab and Mathematica represent tensors (multi-dimensional arrays), of which I will stress three: Matrices in Matlab are stored in the column-major order (like in Fortran and R), while in Mathematica they are stored in the row-major order (like in C). This is ...


10

If you make all the component parts matrices, you can use ArrayFlatten c = {{{{1}}, {{2, 3, 4}}}, {{{5}, {9}}, {{6, 7, 8}, {10, 11, 12}}}}; c // MatrixForm ArrayFlatten[c] // MatrixForm


9

Leonid has given you the theory behind why the dimensions get flipped — it's because of how arrays are indexed. However, I offer a much simpler way of doing the transformation using the powerful second argument of Flatten. First, let's create an example in MATLAB: mat = reshape(magic(32),[1,2,4,8,16]); size(mat) % ans = 1 2 4 8 16 ...


9

I don't belive there is a build in function for this, however you can easily do it using Range fSpace[min_, max_, steps_, f_: Log] := InverseFunction[f] /@ Range[f@min, f@max, (f@max - f@min)/(steps - 1)] Inverse functions are being used so it'll give warnings in cases where you should be cautius, however it works for Log and other invertible ...


9

Based on the description you provided from the MATLAB documentation, corr2 is computed as $$\frac{\sum_m \sum_n (A_{mn} - \bar{A}) (B_{mn} - \bar{B})}{\sqrt{\left(\sum_m \sum_n (A_{mn} - \bar{A})^2\right) \left(\sum_m \sum_n (B_{mn} - \bar{B})^2\right)}} $$ Assuming that the mean2 function that gives the values of $ \bar{A} $ and $ \bar{B} $ does the ...


8

I'll leave this up on GitHub, but I won't maintain the port. I recommend using MATLink instead. There's a package on the Wolfram Library Archive called mEngine that allows calling MATLAB from Mathematica. What it can do is: execute arbitrary MATLAB commands and retrieve their output as a string transfer array variables between Mathematica and MATLAB ...


8

Alternatively: newcolor = RGBColor /@ {{0, 0, 0}, {0.2`, 0, 0}, {0.4`, 0, 0}, {0.6`, 0, 0}, {0.8`, 0, 0}, {1, 0, 0}, {1, 0.2`, 0}, {1, 0.4`, 0}, {1, 0.6`, 0}, {1, 0.8`, 0}, {1, 1, 0}, {1, 1, 0.2`}, {1, 1, 0.4`}, {1, 1, 0.6`}, {1, 1, 0.8`}, {1, 1, 1}}; dat = With[{y = Range[-2, 2, .04]}, Table[Exp[-x^2 - y^2], {x, y}]]; ListDensityPlot[dat, ...


8

Bear in mind that I'm not completely sure what you are calculating, here is my 5 cents towards what can help you get a better performance. I haven't benched marked the MATLAB code on my system, but the changes implemented in Mathematica lead to a runtime decrease from 78.036 s down to to 0.171 s. The slowing factors where mainly that you handle a lot of ...


8

I believe you need to specify n and convert everything to reals: "[" <> StringJoin[ Riffle[StringSplit[ExportString[N@m, "Table"], "\n"] , ";"]] <> "]" ( with n=3 ) [0. 0. 5.291502622129181 0. 2.6457513110645907 0. 0. 0. 2.6457513110645907 0. 0. 0. 0. 0. 0. 0. ; 0. 0. 0. 4.898979485566356 0. 2.449489742783178 ...


7

Your question is a bit confusing to me because imshow and DensityPlot do different things. imshow will take a matrix of values and show it as an image. The Mathematica equivalent is Image. DensityPlot will take a two-argument function and plot it in 2D. Here's a direct comparison (using MATLink to pass the data to MATLAB, for convenience): If you need ...


7

There are already good explanations about how the restructuring of the nested arrays given as input to cell2mat can be done in Mathematica. I couldn't resist to mention the following, though: The main purpose of the matlab function cell2mat is to convert from so called cell arrays to "normal" matlab matrices, where cell arrays correspond roughly to "normal" ...


7

How to make the numerical Fourier transform match up exactly with the analytical one? I'll just work a 1-dimensional example here, but it should apply in 2D as well. We take a Gaussian pulse whose phase is zero at time zero, and it should have a completely real and positive Fourier transformation pulse[t_] := Exp[-t^2/ (2 σ^2)] Exp[-I ω0 t]; pulseω = ...


6

c = {{{1}, {2, 3, 4}}, {{{5}, {9}}, {{6, 7, 8}, {10, 11, 12}}}}; This works for this example, perhaps you can tweak it to your needs. Switch[Depth[#], 3, Join @@ #, 4, Sequence @@ Join @@@ Transpose[#]] & /@ c


6

If you want to translate Matlab code into Mathematica, my advice is - don't! As programming languages, the two are very different and an idiom that works well in one is unlikely to work well in the other. A fundamental theorem theorem in discrete dynamics states that if there's an attractive orbit, then it must attract at least one critical point. Thus, ...



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