# Matlab 2017a mex of mandelbrot_step.c

1 view (last 30 days)
Bert RAM Aerts on 12 Mar 2017
Commented: Bert RAM Aerts on 12 Mar 2017
In the book "Experiments with Matlab" of Cleve Moler (free ebook)
with source code
In chapter "Mandelbrot set" there is a file mandelbrot_step.c which can be compiled by mex.
Now in R2017a this fails even with -compatibleArrayDims from 64 bit api changes
Matlab crashes on it.
What should change in
#include <math.h>
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
/* function [z,kz] = mandelbrot_step(z,kz,z0,d);
* Take one step of the Mandelbrot iteration.
* Complex arithmetic:
* z = z.^2 + z0
* kz(abs(z) < 2) == d
* Real arithmetic:
* x <-> real(z);
* y <-> imag(z);
* u <-> real(z0);
* v <-> imag(z0);
* [x,y] = [x.^2-y.^2+u, 2*x.*y+v];
* kz(x.^2+y.^2 < 4) = d;
*/
{
double *x,*y,*u,*v,t;
unsigned short *kz,d;
int j,n;
x = mxGetPr(prhs);
y = mxGetPi(prhs);
kz = (unsigned short *) mxGetData(prhs);
u = mxGetPr(prhs);
v = mxGetPi(prhs);
d = (unsigned short) mxGetScalar(prhs);
plhs = prhs;
plhs = prhs;
n = mxGetN(prhs);
for (j=0; j<n*n; j++) {
if (kz[j] == d-1) {
t = x[j];
x[j] = x[j]*x[j] - y[j]*y[j] + u[j];
y[j] = 2*t*y[j] + v[j];
if (x[j]*x[j] + y[j]*y[j] < 4) {
kz[j] = d;
}
}
}
return;
}
My mex compiler is Microsoft Visual Studio 2015 Community Edition.

Jan on 12 Mar 2017
unsigned short ==> uint16_T
int ==> size_t
Writing into the input array and replying it as output is, well, bold. The officially supported way is (James, please correct me on demand):
plhs = mxDuplicateArray(prhs);
plhs = mxDuplicateArray(prhs);
x = mxGetPr(plhs);
y = mxGetPi(plhs);
kz = (uint16_T *) mxGetData(plhs);
u = mxGetPr(prhs);
v = mxGetPi(prhs);
d = (unsigned short) mxGetScalar(prhs);
Bert RAM Aerts on 12 Mar 2017
I changed int into mwSize, as this is advised for arrays bigger than 2^32-1.
Indeed you are perfectly right that plhs=prhs is a tricky statement.
With your corrections it now works just fine.
Thanks!

### Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!