CodePlexProject Hosting for Open Source Software

#include "au_mex.h" // Declare mlx_function (C++ version of mexFunction) void mlx_function(mlx_inputs& in, mlx_outputs& out) { mlx_array<double> A(in[0]); // Get input 0 mlx_array<double> B(in[1]); // Get input 1 mlx_make_array<double> sum(A.size); // Make output array // Perform the operation for(int i = 0; i < A.numel(); ++i) sum[i] = A[i] + B[i]; out[0] = sum; // Assign to output }

If you don't like the predeclared mexFunction (which just wraps its inputs and calls mlx_function), you can #define MLX_NO_MEXFUNCTION before including au_mex.h.

See the raw mexFunction to see the non-c++ version.

#include "au_mex.h" void mlx_function(mlx_inputs& in, mlx_outputs& out) { mlx_array<double> A(in[0]); // Get input 0 mlx_array<double> B(in[1]); // Get input 1 mlx_assert(A.size == B.size);// Check sizes match mlx_make_array<double> sum(A.size); // Make output array // Perform the operation for(int i = 0; i < A.numel(); ++i) sum[i] = A[i] + B[i]; out[0] = sum; // Assign to output }

Having trouble remembering which Matlab datatype corresponds to which C++ one? We've typedeffed them handily for you:

typedef ... mlx_uint8; typedef ... mlx_uint16; typedef ... mlx_uint32; typedef ... mlx_uint64; typedef ... mlx_single; // etc typedef ... mlx_double; // etc

Want to check if an array is a certain type? Try this:

if (mlx_isa<double>(a_ptr)) { // it is... }

And now let's see the full templated glory of the type dispatch example. First, we write a function template that does our operation

#include "au_mex.h" template <class Real> mlx_array<Real> Compute(mlx_array<Real> const& A, mlx_array<Real> const& B) { mlx_assert(A.size == B.size);// Check sizes match mlx_make_array<Real> sum(A.size); // Make output array // Perform the operation for(int i = 0; i < A.numel(); ++i) sum[i] = A[i] + B[i]; return sum; }

template <class Real> bool try_cast(mxArray const* pA, mxArray const* pB, mlx_output* out) { if (!(mlx_isa<Real>(pA) && mlx_isa<Real>(pB))) return false; // Return silently if types don't match. mlx_array<Real> A(pA); mlx_array<Real> B(pB); *out = Compute(A, B); return true; }

void mlx_function(mlx_inputs& in, mlx_outputs& out) { // Enumerate the types. You really do have to do this, so that the // C++ compiler can lay down different code for each case. // You could clean this up with a macro if you like that sort of thing. if (try_cast<mlx_double>(in[0], in[1], &out[0])) return; if (try_cast<mlx_single>(in[0], in[1], &out[0])) return; if (try_cast<mlx_uint8>(in[0], in[1], &out[0])) return; // If we get here, mexErrMsgIdAndTxt("awful:types", "We don't handle this input type combo: %s, %s", mxGetClassName(in[0]), mxGetClassName(in[1])); }

Last edited Aug 20, 2015 at 4:49 PM by awfidius, version 23