%% Setting up mex

% on 64-bit systems, a complier must be installed.  For windows you can use
% the free visual studio express from microsoft along with the SDK:

%http://www.mathworks.com/support/solutions/en/data/1-DLG5NF/index.html?solution=1-DLG5NF

%The first time you use 'mex', you need to set which complier you would
%like to use.  On windows machines, MATLAB comes with a compiler, 'lcc'.
%For linux and Mac OSX, the gcc complier must be installed (its free). 

%to set the compiler:

mex -setup


% the matlab documentation is fairly good for creating mex files.
doc mex 

% check if everthing is working by compiling one of matlab's mex example
% files

curdir=pwd; %save your current directory

%move to the dirctory with example c-code
cd([matlabroot '/extern/examples/refbook']) %windows only??

%compile one of the c-files
mex convec.c

%if this works, it should generate a *.mex* file (*.mexw32 for 32 bit
%windows). 

% move back to you old directory

a=rand(5,1)'
b=rand(5,1)'
convec(a+b*i,a+b*i)

cd(curdir)

%% Creating a mex file

%here is the file we created.  See internal comments. 
edit  cMEXexample.c


%% Compiling a mex file

% the '-O' is an optimization flag. 
mex -O cMEXexample.c

%% Calling a mex file

A= 3*ones(5,2)
B= 2*ones(5,2)

C=cMEXexample(A,B)


%testing our error handling:
A= 3*ones(5,2)
B= 2*ones(2,5)
C=cMEXexample(A,B)

A= 3*ones(10,10)
B= 2*ones(5,5)
C=cMEXexample(A,B)

A= 3*ones(5,10)
B= 2*ones(5,5)
C=cMEXexample(A,B)

A= single(3*ones(5,5))
B= single(2*ones(5,5))
C=cMEXexample(A,B)
% this last one runs, but gives the wrong answer! We didn't check the 
% input data type and assumed it was 'double', the matlab default type. 









