<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mex &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/category/mex/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 18 Jul 2018 14:56:44 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Multi-threaded Mex</title>
		<link>https://undocumentedmatlab.com/articles/multi-threaded-mex?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=multi-threaded-mex</link>
					<comments>https://undocumentedmatlab.com/articles/multi-threaded-mex#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 18 Jul 2018 14:56:44 +0000</pubDate>
				<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7771</guid>

					<description><![CDATA[<p>Tips for creating and debugging multi-threaded Mex functions are discussed. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/multi-threaded-mex">Multi-threaded Mex</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part4" rel="bookmark" title="Explicit multi-threading in Matlab part 4">Explicit multi-threading in Matlab part 4 </a> <small>Matlab performance can be improved by employing timer objects and spawning external processes. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3" rel="bookmark" title="Explicit multi-threading in Matlab part 3">Explicit multi-threading in Matlab part 3 </a> <small>Matlab performance can be improved by employing POSIX threads in C/C++ code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part2" rel="bookmark" title="Explicit multi-threading in Matlab part 2">Explicit multi-threading in Matlab part 2 </a> <small>Matlab performance can be improved by employing .Net (C#, VB, F# or C++) threads. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-line-uitable-column-headers" rel="bookmark" title="Multi-line uitable column headers">Multi-line uitable column headers </a> <small>Matlab uitables can present long column headers in multiple lines, for improved readability. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I was recently asked by a consulting client to help speed up a Matlab process. <span class="alignright"><img decoding="async" src="https://undocumentedmatlab.com/images/speedometer4d_200x200.gif" alt="Accelerating MATLAB Performance" title="Accelerating MATLAB Performance" width="200" height="200" /></span> Quite often there are various ways to improve the run-time, and in this particular case it turned out that the best option was to convert the core Matlab processing loop into a multi-threaded Mex function, while keeping the rest (vast majority of program code) in easy-to-maintain Matlab. This resulted in a 160x speedup (25 secs => 0.16 secs). Some of this speedup is attributed to C-code being faster in general than Matlab, another part is due to the multi-threading, and another due to <a href="/articles/matlab-mex-in-place-editing" target="_blank">in-place data manipulations</a> that avoid costly memory access and re-allocations.<br />
In today&#8217;s post I will share some of the insights relating to this MEX conversion, which could be adapted for many other similar use-cases. Additional Matlab speed-up techniques can be found in other <a href="/articles/tag/performance" target="_blank">performance-related posts</a> on this website, as well in my book <a href="/books/matlab-performance" target="_blank"><b>Accelerating MATLAB Performance</b></a>.<br />
There are quite a few online resources about creating Mex files, so I will not focus on this aspect. I&#8217;ll assume that the reader is already familiar with the concept of using Mex functions, which are simply dynamically-linked libraries that have a predefined entry-function syntax and predefined platform-specific extension. Instead, I&#8217;ll focus on how to create and debug a multi-threaded Mex function, so that it runs in parallel on all CPU cores.<br />
The benefit of multi-<i>threading</i> is that threads are very light-weight objects, that have minimal performance and memory overheads. This contrasts to multi-<i>tasking</i>, which is what the Parallel Computing Toolbox currently does: launches duplicate copies of the entire Matlab engine process (&#8220;headless workers&#8221;) and then manages and coordinates the tasks to split up the processing work. Multi-tasking should be avoided wherever we can employ light-weight multi-threading instead. Unfortunately, Matlab does not currently have the ability to explicitly multi-thread Matlab code. But we can still use explicit multi-threading by invoking code in other languages, as I&#8217;ve already shown for <a href="/articles/explicit-multi-threading-in-matlab-part1" target="_blank">Java</a>, <a href="/articles/explicit-multi-threading-in-matlab-part2" target="_blank">C# (and .NET in general)</a>, and <a href="/articles/explicit-multi-threading-in-matlab-part3" target="_blank">C/C++</a>. Today&#8217;s article will expand on the latter post (the one about C/C++ multi-threading), by showing a general framework for making a multi-threaded C-based Mex function.<br />
<span id="more-7771"></span><br />
There are several alternative implementation of threads. On non-Windows machines, POSIX threads (&#8220;pthreads&#8221;) are a de-facto standard; on Windows, which pthreads can still be used, they generally use native Windows threads under the hood, and we can use these native threads directly.<br />
I have uploaded a file called <a href="https://www.mathworks.com/matlabcentral/fileexchange/68237-max_in_place-example-of-multi-threaded-mex-function" rel="nofollow" target="_blank">max_in_place</a> to the Matlab File Exchange. This function serves as an example showing a generic multi-threaded Mex function. A compiled version of this Mex file for Win64 is also included in the File Exchange entry, and you can run it directly on a Win64 machine.<br />
The usage in Matlab is as follows (note how <code>matrix1</code> is updated in-place):</p>
<pre lang="matlab">
>> matrix1 = rand(4)
matrix1 =
      0.89092      0.14929      0.81428      0.19664
      0.95929      0.25751      0.24352      0.25108
      0.54722      0.84072      0.92926      0.61604
      0.13862      0.25428      0.34998      0.47329
>> matrix2 = rand(4)
matrix2 =
      0.35166      0.91719      0.38045      0.53081
      0.83083      0.28584      0.56782      0.77917
      0.58526       0.7572     0.075854      0.93401
      0.54972      0.75373      0.05395      0.12991
>> max_in_place(matrix1, matrix2)
>> matrix1
matrix1 =
      0.89092      0.91719      0.81428      0.53081
      0.95929      0.28584      0.56782      0.77917
      0.58526      0.84072      0.92926      0.93401
      0.54972      0.75373      0.34998      0.47329
</pre>
<h3 id="source-code">Source code and discussion</h3>
<p>The pseudo-code for the MEX function is as follows:</p>
<pre lang="text">
mexFunction():
   validate the input/output args
   quick bail-out if empty inputs
   get the number of threads N from Matlab's maxNumCompThreads function
   if N == 1
       run main_loop directly
   else
       split input matrix #1 into N index blocks
       assign start/end index for each thread
       create and launch N new threads that run main_loop
       wait for all N threads to complete
       free the allocated memory resources
   end
</pre>
<p>Here&#8217;s the core source-code of this function, which was adapted from original work by <a href="https://www.mathworks.com/matlabcentral/profile/authors/1097878-dirk-jan-kroon" rel="nofollow" target="_blank">Dirk-Jan Kroon</a>:</p>
<pre lang="cpp">
/*====================================================================
 *
 * max_in_place.c  updates a data matrix in-place with the max value
 *                 of the matrix and a 2nd matrix of the same size
 *
 * The calling syntax is:
 *
 *		max_in_place(matrix1, matrix2)
 *
 * matrix1 will be updated with the maximal values from corresponding
 * indices of the 2 matrices
 *
 * Both inputs must be double 2D real non-sparse matrices of same size
 *
 * Yair Altman 2018-07-18
 * https://UndocumentedMatlab.com/articles/multi-threaded-mex
 *
 * Adapted from original work by Dirk-Jan Kroon
 * http://mathworks.com/matlabcentral/profile/authors/1097878-dirk-jan-kroon
 *
 *==================================================================*/
#include <math.h>
#include "mex.h"
/* undef needed for LCC compiler */
#undef EXTERN_C
#ifdef _WIN32
    #include <windows.h>
    #include <process.h>
#else
    #include <pthread.h>
#endif
/* Input Arguments */
#define	hMatrix1	prhs[0]
#define	hMatrix2	prhs[1]
/* Macros */
#if !defined(MAX)
#define	MIN(A, B)	((A) < (B) ? (A) : (B))
#endif
/* Main processing loop function */
void main_loop(const mxArray *prhs[], int startIdx, int endIdx)
{
    /* Assign pointers to the various parameters */
    double *p1 = mxGetPr(hMatrix1);
    double *p2 = mxGetPr(hMatrix2);
    /* Loop through all matrix coordinates */
    for (int idx=startIdx; idx<=endIdx; idx++)
    {
        /* Update hMatrix1 with the maximal value of hMatrix1,hMatrix2 */
        if (p1[idx] < p2[idx]) {
            p1[idx] = p2[idx];
        }
    }
}
/* Computation function in threads */
#ifdef _WIN32
  unsigned __stdcall thread_func(void *ThreadArgs_) {
#else
  void thread_func(void *ThreadArgs_) {
#endif
    double **ThreadArgs = ThreadArgs_;  /* void* => double** */
    const mxArray** prhs = (const mxArray**) ThreadArgs[0];
    int ThreadID = (int) ThreadArgs[1][0];
    int startIdx = (int) ThreadArgs[2][0];
    int endIdx   = (int) ThreadArgs[3][0];
    /*mexPrintf("Starting thread #%d: idx=%d:%d\n", ThreadID, startIdx, endIdx); */
    /* Run the main processing function */
    main_loop(prhs, startIdx, endIdx);
    /* Explicit end thread, helps to ensure proper recovery of resources allocated for the thread */
    #ifdef _WIN32
        _endthreadex( 0 );
        return 0;
    #else
        pthread_exit(NULL);
    #endif
}
/* validateInputs function here... */
/* Main entry function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    /* Validate the inputs */
    validateInputs(nlhs, plhs, nrhs, prhs);
    /* Quick bail-out in the trivial case of empty inputs */
    if (mxIsEmpty(hMatrix1))  return;
    /* Get the number of threads from the Matlab engine (maxNumCompThreads) */
    mxArray *matlabCallOut[1] = {0};
    mxArray *matlabCallIn[1]  = {0};
    mexCallMATLAB(1, matlabCallOut, 0, matlabCallIn, "maxNumCompThreads");
    double *Nthreadsd = mxGetPr(matlabCallOut[0]);
    int Nthreads = (int) Nthreadsd[0];
    /* Get the number of elements to process */
    size_t n1 = mxGetNumberOfElements(hMatrix1);
    if (Nthreads == 1) {
        /* Process the inputs directly (not via a thread) */
        main_loop(prhs, 0, n1-1);
    } else {  /* multi-threaded */
        /* Allocate memory for handles of worker threads */
        #ifdef _WIN32
            HANDLE    *ThreadList = (HANDLE*)   malloc(Nthreads*sizeof(HANDLE));
        #else
            pthread_t *ThreadList = (pthread_t*)malloc(Nthreads*sizeof(pthread_t));
        #endif
        /* Allocate memory for the thread arguments (attributes) */
        double **ThreadID, **ThreadStartIdx, **ThreadEndIdx, ***ThreadArgs;
        double *ThreadID1, *ThreadStartIdx1, *ThreadEndIdx1, **ThreadArgs1;
        ThreadID       = (double **) malloc( Nthreads* sizeof(double *) );
        ThreadStartIdx = (double **) malloc( Nthreads* sizeof(double *) );
        ThreadEndIdx   = (double **) malloc( Nthreads* sizeof(double *) );
        ThreadArgs     = (double ***)malloc( Nthreads* sizeof(double **) );
        /* Launch the requested number of threads */
        int i;
        int threadBlockSize = ceil( ((double)n1) / Nthreads );
        for (i=0; i<nthreads; i++)
        {
            /* Create thread ID */
            ThreadID1 = (double *)malloc( 1* sizeof(double) );
            ThreadID1[0] = i;
            ThreadID[i] = ThreadID1;
            /* Compute start/end indexes for this thread */
            ThreadStartIdx1 = (double *) malloc( sizeof(double) );
            ThreadStartIdx1[0] = i * threadBlockSize;
            ThreadStartIdx[i] = ThreadStartIdx1;
            ThreadEndIdx1 = (double *) malloc( sizeof(double) );
            ThreadEndIdx1[0] = MIN((i+1)*threadBlockSize, n1) - 1;
            ThreadEndIdx[i] = ThreadEndIdx1;
            /* Prepare thread input args */
            ThreadArgs1 = (double **) malloc( 4* sizeof(double*) );
            ThreadArgs1[0] = (double *) prhs;
            ThreadArgs1[1] = ThreadID[i];
            ThreadArgs1[2] = ThreadStartIdx[i];
            ThreadArgs1[3] = ThreadEndIdx[i];
            ThreadArgs[i] = ThreadArgs1;
            /* Launch the thread with its associated args */
            #ifdef _WIN32
                ThreadList[i] = (HANDLE)_beginthreadex(NULL, 0, &#038;thread_func, ThreadArgs[i], 0, NULL);
            #else
                pthread_create ((pthread_t*)&#038;ThreadList[i], NULL, (void *) &#038;thread_func, ThreadArgs[i]);
            #endif
        }
        /* Wait for all the treads to finish working */
        #ifdef _WIN32
            for (i=0; i<nthreads; i++) { WaitForSingleObject(ThreadList[i], INFINITE); }
            for (i=0; i<nthreads; i++) { CloseHandle( ThreadList[i] ); }
        #else
            for (i=0; i<nthreads; i++) { pthread_join(ThreadList[i],NULL); }
        #endif
        /* Free the memory resources allocated for the threads */
        for (i=0; i<nthreads; i++)
        {
            free(ThreadArgs[i]);
            free(ThreadID[i]);
            free(ThreadStartIdx[i]);
            free(ThreadEndIdx[i]);
        }
        free(ThreadArgs);
        free(ThreadID );
        free(ThreadStartIdx);
        free(ThreadEndIdx);
        free(ThreadList);
    }
    return;
}
</pre>
<p>This file also includes a <i>validateInputs</i> function. I did not include it in the code snippet above for brevity; you can read it directly in the FEX entry (<i>max_in_place.c</i>). This function checks that there are exactly 0 output and 2 input args, that the input args are real non-sparse matrices and that they have the same number of elements.<br />
Note that the threads run a generic <i>thread_func</i> function, which in turn runs the <i>main_loop</i> function with the thread's specified <code>startIndex</code>, <code>endIndex</code> values. When this function completes, the thread ends itself explicitly, to ensure resource cleanup.<br />
Also note how the thread code is using pthreads on non-Windows (<code>!defined(_WIN32)</code>) machines, and native Windows threads otherwise. This means that the same MEX source-code could be used on all Matlab platforms.<br />
The important thing to note about this framework is that we no longer need to worry about the thread plumbing. If we wish to adapt this code for any other processing, we just need to modify the <i>main_loop</i> function with the new processing logic. In addition, you may wish to modify the <i>validateInputs</i> function based on your new setup of input/output args.<br />
A few caveats:</p>
<ul>
<li>On Windows machines with R2017b or older, we simply compile using <code>mex max_in_place.c</code>; on non-Windows we might need to add the <code>–lpthread</code> flag to link the pthreads library, depending on your specific compiler.</li>
<li>On R2018a or newer on all platforms, due to MEX's new <a href="https://www.mathworks.com/help/matlab/matlab_external/matlab-support-for-interleaved-complex.html" rel="nofollow" target="_blank">interleaved-complex memory format</a>, we would need to compile with the <code>-R2017b</code> flag if we wish to use <i><a href="https://www.mathworks.com/help/matlab/apiref/mxgetpr.html" rel="nofollow" target="_blank">mexGetPr</a></i>, as in the sample code above (in R2018a's new data model, the corresponding function is <i><a href="https://www.mathworks.com/help/matlab/apiref/mxgetdoubles.html" rel="nofollow" target="_blank">mxGetDoubles</a></i>). Note that updating data in-place becomes more difficult with the new MEX API, so if you want to preserve the performance boost that in-place data manipulation provides, it may be better to stick with the legacy data memory model.</li>
<li>The sample code above splits the data between the threads based on the first input matrix's size. Instead, you may consider sending to the MEX function the loop indexes as extra input args, and then splitting those up between the threads.</li>
<li>In this specific implementation of <i>max_in_place</i>, I have updated the data locations directly. This is generally discouraged and risky, because it conflicts with Matlab's standard Copy-on-Write mechanism. For example, if we assign the input to any other Matlab variable(s) before calling <i>max_in_place</i>, then that other variable(s) will also get their data updated. If we do not want this side-effect, we should <a href="/articles/matlab-mex-in-place-editing" target="_blank">mxUnshareArray</a> the input matrix1, and return the resulting matrix as an output of the MEX function (<code>plhs[0]</code>).</li>
</ul>
<h3 id="tips">Speed-up tips</h3>
<p>The core logic in the specific case that I was asked to optimize was something similar to this:</p>
<pre lang="text">
main_process:
    initialize output matrix
    loop z over all slices in a 3D data matrix
        temp_data = data(:,:,z);
        temp_data = process(temp_data);
        output = max(output, temp_data);
    end z loop
</pre>
<p>The initial speed-up attempt was naturally focused on the <code>process</code> and <code>max</code> functions. Converting them to a MEX function improved the speed by a factor of ~8, but the resulting run-time (4-5 secs) was still too slow for real-time use. The reason that we did not see a larger speed-up was, I believe, due to several reasons:</p>
<ul>
<li><code>temp_data</code> was small enough such that the overheads associated with creating and then disposing separate threads were significant compared to the processing time of each thread.</li>
<li><code>temp_data</code> was small enough such that each thread processed a relatively small portion of the memory, in contrast to single-threaded processing that accesses memory in larger blocks, more efficiently.</li>
<li>In each iteration of the z loop, the overheads associated with calling the MEX function, handling input variables and validation, creating/disposing threads, and allocating/deallocating memory for <code>temp_data</code>, were repeatedly paid.</li>
</ul>
<p>So, while the profiling result showed that 98% of the time was spent in the MEX function (which would seem to indicate that not much additional speedup can be achieved), in fact the MEX function was under-performing because of the inefficiencies involved in repeatedly creating threads to process small data chunks. It turned out that running in single-thread mode was actually somewhat faster than multi-threaded mode.<br />
I then moved the entire z loop (entire <code>main_process</code>) into the MEX function, where the threads were split to process separate adjacent blocks of z slices (i.e. different blocks of the z loop). This way, the MEX function was called, the inputs validated, and threads created/disposed only once for the entire process, making this overhead negligible compared to each thread's processing time. Moreover, each thread now processed the entire <code>temp_data</code> belonging to its z slice, so memory access was more efficient, reducing the memory I/O wait time and improving the overall processing time. Additional benefits were due to the fact that some variables could be reused within each thread across loop iterations, minimizing memory allocations and deallocations. The overall effect was to reduce the total run-time down to ~0.16 secs, a 160x speedup compared to the original (25 secs). As my client said: "<i>You sped up [the application] from practically useless to clinically useful</i>."<br />
The lesson: try to minimize MEX invocation and thread creation/disposal overheads, and let the threads process as large adjacent memory blocks as possible.</p>
<h3 id="debugging">Debugging MEX files</h3>
<p>When debugging multi-threaded MEX functions, I find that it's often easier to run the function in single-threaded mode to debug the core logic, and once this is ready we can switch back multi-threading. This can easily be done by setting the number of threads outside the MEX function using Matlab's builtin <i><b><a href="https://www.mathworks.com/help/matlab/ref/maxnumcompthreads.html" rel="nofollow" target="_blank">maxNumCompThreads</a></b></i> function:</p>
<pre lang="matlab">
Nthreads = maxNumCompThreads(1);  % temporarily use only 1 thread for debugging
max_in_place(matrix1, matrix2);
maxNumCompThreads(Nthreads);      % restore previous value
%maxNumCompThreads('automatic');  % alternative
</pre>
<p>Once debugging is done and the MEX function works properly, we should remove the <i><b>maxNumCompThreads</b></i> calls, so that the MEX function will use the regular number of Matlab computational threads, which should be the same as the number of cores: <a href="/articles/undocumented-feature-function" target="_blank">feature('numCores')</a>.<br />
I typically like to use Eclipse as my IDE for non-Matlab code (Java, C/C++ etc.). Unfortunately, there's a problem attaching Eclipse to Matlab processes (which is necessary for interactive MEX debugging) if you're using any recent (post-2015) version of MinGW and Eclipse. This problem is due to a <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=474311" rel="nofollow" target="_blank">known Eclipse bug</a>, as user Lithe <a href="https://www.mathworks.com/matlabcentral/answers/241291-how-to-debug-mex-file-compiled-with-mingw64-and-g-flags#comment_461391" rel="nofollow" target="_blank">pointed out</a>. The workaround is to install an old version of MinGW, *in addition* to your existing MinGW version. <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=474311#c15" rel="nofollow" target="_blank">Reportedly</a>, only versions <a href="https://sourceforge.net/projects/tdm-gcc/files/TDM-GCC%20Installer/Previous/1.1309.0/" rel="nofollow" target="_blank">4.9.1 or older</a> of MinGW include gdb 7.8 (which is still supported by Eclipse), whereas newer versions of MinGW include a newer gdb that is not supported. Download and install such an old MinGW version in a separate folder from your more-modern compiler. Don't update your MEX to use the older MinGW - just tell Eclipse to use the version of gdb in the old MinGW bin/ folder when you set up a debug configuration for debugging your MEX files.<br />
Once you have a compatible gdb, and ask Eclipse to attach to a process, the processes list will finally appear (it won't with an incompatible gdb). Use <code><a href="/articles/undocumented-feature-function" target="_blank">feature('getPID')</a></code> to get your Matlab process ID, which can then used to attach to the relevant process in the Eclipse Attach-to-process window. For example, if your Matlab's PID is 4321, then the Matlab process will be called "Program - 4321" in Eclipse's processes list.<br />
I wish that MathWorks would update their <a href="https://www.mathworks.com/matlabcentral/answers/241291-how-to-debug-mex-file-compiled-with-mingw64-and-g-flags" rel="nofollow" target="_blank">official Answer</a> and their <a href="https://www.mathworks.com/matlabcentral/fileexchange/52848-matlab-support-for-mingw-w64-c-c-compiler" rel="nofollow" target="_blank">MinGW support package on File Exchange</a> to include this information, because without it debugging on Eclipse becomes impossible. Eclipse is so powerful, easy-to-use and ubiquitous that it's a shame for most users not to be able to work with it just because the workarounds above are not readily explained.<br />
N.B. If you don't like Eclipse, you can also use Visual Studio Code (VS Code), as Andy Campbell <a href="https://blogs.mathworks.com/developer/2018/06/19/mex-debugging-vscode" rel="nofollow" target="_blank">recently explained</a> in the MathWorks Developers' blog.</p>
<h3 id="consulting">Consulting</h3>
<p>Do you have any Matlab code that could use a bit (or a lot) of speeding-up? If so, please <a href="/consulting#request" target="_blank">contact me</a> for a private consulting offer. I can't promise to speed up your code by a similar factor of 160x, but you never know...</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/multi-threaded-mex">Multi-threaded Mex</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part4" rel="bookmark" title="Explicit multi-threading in Matlab part 4">Explicit multi-threading in Matlab part 4 </a> <small>Matlab performance can be improved by employing timer objects and spawning external processes. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3" rel="bookmark" title="Explicit multi-threading in Matlab part 3">Explicit multi-threading in Matlab part 3 </a> <small>Matlab performance can be improved by employing POSIX threads in C/C++ code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part2" rel="bookmark" title="Explicit multi-threading in Matlab part 2">Explicit multi-threading in Matlab part 2 </a> <small>Matlab performance can be improved by employing .Net (C#, VB, F# or C++) threads. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-line-uitable-column-headers" rel="bookmark" title="Multi-line uitable column headers">Multi-line uitable column headers </a> <small>Matlab uitables can present long column headers in multiple lines, for improved readability. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/multi-threaded-mex/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Faster csvwrite/dlmwrite</title>
		<link>https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=faster-csvwrite-dlmwrite</link>
					<comments>https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Tue, 03 Oct 2017 15:00:05 +0000</pubDate>
				<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7080</guid>

					<description><![CDATA[<p>The speed of the builtin csvwrite, dlmwrite functions can be improved dramatically. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite">Faster csvwrite/dlmwrite</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/faster-findjobj" rel="bookmark" title="Faster findjobj">Faster findjobj </a> <small>the ubiquitous findjobj utility has been significantly improved for speed for the most common use case. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt" rel="bookmark" title="MEX ctrl-c interrupt">MEX ctrl-c interrupt </a> <small>An undocumented MEX function can help interrupt running MEX functions. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matrix-processing-performance" rel="bookmark" title="Matrix processing performance">Matrix processing performance </a> <small>Matrix operations performance is affected by internal subscriptions in a counter-intuitive way....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3" rel="bookmark" title="Explicit multi-threading in Matlab part 3">Explicit multi-threading in Matlab part 3 </a> <small>Matlab performance can be improved by employing POSIX threads in C/C++ code. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab&#8217;s builtin functions for exporting (saving) data to output files are quite sub-optimal (as in <i>slowwwwww&#8230;</i>). I wrote a few posts about this in the past (how to improve <a href="/articles/improving-fwrite-performance" target="_blank"><i><b>fwrite</b></i> performance</a>, and <a href="/articles/improving-save-performance" target="_blank"><i><b>save</b></i> performance</a>). Today I extend the series by showing how we can improve the performance of delimited text output, for example comma-separated (CSV) or tab-separated (TSV/TXT) files.<br />
The basic problem is that Matlab&#8217;s <i><b>dlmwrite</b></i> function, which can either be used directly, or via the <i><b>csvwrite</b></i> function which calls it internally, is extremely inefficient: It processes each input data value separately, in a non-vectorized loop. In the general (completely non-vectorized) case, each data value is separately converted into a string, and is separately sent to disk (using <i><b>fprintf</b></i>). In the specific case of real data values with simple delimiters and formatting, row values are vectorized, but in any case the rows are processed in a non-vectorized loop: A newline character is separately exported at the end of each row, using a separate <i><b>fprintf</b></i> call, and this has the effect of flushing the I/O to disk each and every row separately, which is of course disastrous for performance. The output file is indeed originally opened in buffered mode (as I explained in my <a href="/articles/improving-fwrite-performance" target="_blank"><i><b>fprintf</b></i> performance</a> post), but this only helps for outputs done within the row &#8211; the newline output at the end of each row forces an I/O flush regardless of how the file was opened. In general, when you read the short source-code of <i>dlmwrite.m</i> you&#8217;ll get the distinct feeling that it was written for correctness and maintainability, and some focus on performance (e.g., the vectorization edge-case). But much more could be done for performance it would seem.<br />
This is where Alex Nazarovsky comes to the rescue.<br />
<span id="more-7080"></span><br />
Alex was so bothered by the slow performance of <i><b>csvwrite</b></i> and <i><b>dlmwrite</b></i> that he created a C++ (MEX) version that runs about enormously faster (30 times faster on my system). He <a href="http://nazarovsky.ru/2014/08/22/fast-csv-values-export-to-file-mex-based-dlmwrite-replacement-for-matlab" rel="nofollow" target="_blank">explains the idea</a> in his blog, and posted it as an open-source utility (<a href="https://github.com/nazarovsky/mex-writematrix" rel="nofollow" target="_blank">mex-writematrix</a>) on GitHub.<br />
Usage of Alex&#8217;s utility is very easy:</p>
<pre lang="matlab">mex_WriteMatrix(filename, dataMatrix, textFormat, delimiter, writeMode);</pre>
<p>where the input arguments are:</p>
<ul>
<li>filename &#8211; full path name for file to export</li>
<li>dataMatrix &#8211; matrix of numeric values to be exported</li>
<li>textFormat &#8211; format of output text (<i><b>sprintf</b></i> format), e.g. <code>'%10.6f'</code></li>
<li>delimiter &#8211; delimiter, for example <code>','</code> or <code>';'</code> or <code>char(9)</code> (=tab)</li>
<li>writeMode &#8211; <code>'w+'</code> for rewriting file; <code>'a+'</code> for appending (note the lowercase: uppercase will crash Matlab!)</li>
</ul>
<p>Here is a sample run on my system, writing a simple CSV file containing 1K-by-1K data values (1M elements, ~12MB text files):</p>
<pre lang="matlab">
>> data = rand(1000, 1000);  % 1M data values, 8MB in memory, ~12MB on disk
>> tic, dlmwrite('temp1.csv', data, 'delimiter',',', 'precision','%10.10f'); toc
Elapsed time is 28.724937 seconds.
>> tic, mex_WriteMatrix('temp2.csv', data, '%10.10f', ',', 'w+'); toc   % 30 times faster!
Elapsed time is 0.957256 seconds.
</pre>
<p>Alex&#8217;s <i><b>mex_WriteMatrix</b></i> function is faster even in the edge case of simple formatting where <i><b>dlmwrite</b></i> uses vectorized mode (in that case, the file is exported in ~1.2 secs by <i><b>dlmwrite</b></i> and ~0.9 secs by <i><b>mex_WriteMatrix</b></i>, on my system).</p>
<h3 id="ctrl-c">Trapping Ctrl-C interrupts</h3>
<p>Alex&#8217;s <i><b>mex_WriteMatrix</b></i> code includes another undocumented trick that could help anyone else who uses a long-running MEX function, namely the ability to stop the MEX execution using Ctrl-C. Using Ctrl-C is normally ignored in MEX code, but <a href="http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick" rel="nofollow" target="_blank">Wotao Yin showed</a> how we can use the undocumented <i>utIsInterruptPending()</i> MEX function to monitor for user interrupts using Ctrl-C. For easy reference, here is a copy of Wotao Yin&#8217;s usage example (read <a href="http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick" rel="nofollow" target="_blank">his webpage</a> for additional details):</p>
<pre lang="cpp">
/* A demo of Ctrl-C detection in mex-file by Wotao Yin. Jan 29, 2010. */
#include "mex.h"
#if defined (_WIN32)
    #include <windows.h>
#elif defined (__linux__)
    #include <unistd.h>
#endif
#ifdef __cplusplus
    extern "C" bool utIsInterruptPending();
#else
    extern bool utIsInterruptPending();
#endif
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int count = 0;
    while(1) {
        #if defined(_WIN32)
            Sleep(1000);        /* Sleep one second */
        #elif defined(__linux__)
            usleep(1000*1000);  /* Sleep one second */
        #endif
        mexPrintf("Count = %d\n", count++);  /* print count and increase it by 1 */
        mexEvalString("drawnow;");           /* flush screen output */
        if (utIsInterruptPending()) {        /* check for a Ctrl-C event */
            mexPrintf("Ctrl-C Detected. END\n\n");
            return;
        }
        if (count == 10) {
            mexPrintf("Count Reached 10. END\n\n");
            return;
        }
    }
}
</pre>
<h3 id="webinars">Matlab performance webinars</h3>
<p><!--
Next week I will present live online webinars about numerous other ways to improve Matlab's run-time performance:


<ul>
	

<li>Oct 9, 2017 (Mon) - <a target="_blank" href="/courses/Matlab_Performance_Tuning_1_Webinar.pdf">Matlab performance tuning part 1</a> - $295 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&currency_code=USD&business=octahedron.ltd@gmail.com&quantity=1&amount=295&item_name=Matlab+performance+1+webinar" rel="nofollow" target="_blank">buy</a>)</li>


	

<li>Oct 10, 2017 (Tue) - <a target="_blank" href="/courses/Matlab_Performance_Tuning_2_Webinar.pdf">Matlab performance tuning part 2</a> - $295 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&currency_code=USD&business=octahedron.ltd@gmail.com&quantity=1&amount=295&item_name=Matlab+performance+2+webinar" rel="nofollow" target="_blank">buy</a>)
 &nbsp;&nbsp;&nbsp; ==> or buy both Matlab performance tuning webinars for only $495 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&currency_code=USD&business=octahedron.ltd@gmail.com&quantity=1&amount=495&item_name=Matlab+performance+webinars" rel="nofollow" target="_blank">buy</a>)</li>


</ul>


These live webinars will be 3.5 hours long, starting at 10am EDT (7am PDT, 3pm UK, 4pm CET, 7:30pm IST, <a href="https://www.google.com/search?q=9am+edt+to+my+time" rel="nofollow" target="_blank">time in your local timezone</a>), with a short break in the middle. The presentations content will be based on onsite training courses that I presented at multiple client locations (<a href="/training#onsite" target="_blank">details</a>). A recording of the webinars will be available for anyone who cannot join the live events.
--><br />
I am offering a couple of webinars about various ways to improve Matlab&#8217;s run-time performance:</p>
<ul>
<li><a target="_blank" href="/courses/Matlab_Performance_Tuning_1_Webinar.pdf">Matlab performance tuning part 1</a> (3:39 hours, <a target="_blank" href="/courses/Matlab_Performance_Tuning_1_Webinar.pdf">syllabus</a>) &#8211; $195 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&#038;currency_code=USD&#038;business=octahedron.ltd@gmail.com&#038;quantity=1&#038;amount=195&#038;item_name=Matlab+performance+1+webinar" rel="nofollow" target="_blank">buy</a>)</li>
<li><a target="_blank" href="/courses/Matlab_Performance_Tuning_2_Webinar.pdf">Matlab performance tuning part 2</a> (3:43 hours, <a target="_blank" href="/courses/Matlab_Performance_Tuning_2_Webinar.pdf">syllabus</a>) &#8211; $195 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&#038;currency_code=USD&#038;business=octahedron.ltd@gmail.com&#038;quantity=1&#038;amount=195&#038;item_name=Matlab+performance+2+webinar" rel="nofollow" target="_blank">buy</a>)<br />
 &nbsp;&nbsp;&nbsp; ==> or buy both Matlab performance tuning webinars for only $345 (<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&#038;currency_code=USD&#038;business=octahedron.ltd@gmail.com&#038;quantity=1&#038;amount=345&#038;item_name=Matlab+performance+webinars" rel="nofollow" target="_blank">buy</a>)</li>
</ul>
<p>Both the webinar videos and their corresponding slide-decks are available for download. The webinars content is based on onsite training courses that I presented at multiple client locations (<a href="/training#onsite" target="_blank">details</a>).<br />
Additional Matlab performance tips can be found under the <a href="/articles/tag/performance" target="_blank">Performance tag</a> in this blog, as well as in my book &#8220;<a href="/books/matlab-performance" target="_blank"><b>Accelerating MATLAB Performance</b></a>&#8220;.<br />
<a href="mailto: altmany @gmail.com?subject=Matlab webinars&#038;body=Hi Yair, &#038;cc=;&#038;bcc=" rel="nofollow" target="_blank" onclick="var n='altmany'; var d='gmail.com'; window.open('mailto:'+n+'@'+d+'?subject=Matlab webinars&#038;body=Hi Yair, '); return false;"><img decoding="async" src="https://undocumentedmatlab.com/images/email-icon.png" width="32" height="22" alt="" style="vertical-align:middle;border:0"/>&nbsp;Email me</a> if you would like additional information on the webinars, or an onsite training course, or about my consulting.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite">Faster csvwrite/dlmwrite</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/faster-findjobj" rel="bookmark" title="Faster findjobj">Faster findjobj </a> <small>the ubiquitous findjobj utility has been significantly improved for speed for the most common use case. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt" rel="bookmark" title="MEX ctrl-c interrupt">MEX ctrl-c interrupt </a> <small>An undocumented MEX function can help interrupt running MEX functions. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matrix-processing-performance" rel="bookmark" title="Matrix processing performance">Matrix processing performance </a> <small>Matrix operations performance is affected by internal subscriptions in a counter-intuitive way....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3" rel="bookmark" title="Explicit multi-threading in Matlab part 3">Explicit multi-threading in Matlab part 3 </a> <small>Matlab performance can be improved by employing POSIX threads in C/C++ code. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>MEX ctrl-c interrupt</title>
		<link>https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mex-ctrl-c-interrupt</link>
					<comments>https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 15 Jun 2016 17:00:40 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Pavel Holoborodko]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6454</guid>

					<description><![CDATA[<p>An undocumented MEX function can help interrupt running MEX functions. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt">MEX ctrl-c interrupt</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite" rel="bookmark" title="Faster csvwrite/dlmwrite">Faster csvwrite/dlmwrite </a> <small>The speed of the builtin csvwrite, dlmwrite functions can be improved dramatically. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-list" rel="bookmark" title="Undocumented feature list">Undocumented feature list </a> <small>A list of undocumented MATLAB features can be retrieved. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api" rel="bookmark" title="Undocumented Matlab MEX API">Undocumented Matlab MEX API </a> <small>Matlab's MEX API contains numerous undocumented functions, that can be extremely useful. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data" rel="bookmark" title="Serializing/deserializing Matlab data">Serializing/deserializing Matlab data </a> <small>Matlab does not provide a documented manner to serialize data into a byte stream, but we can do this with some undocumented functionality. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I recently became aware of a <a href="http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick/" rel="nofollow" target="_blank">very nice hack</a> by <a href="http://math.ucla.edu/~wotaoyin" rel="nofollow" target="_blank">Wotao Yin</a> (while at Rice in 2010; currently teaching at UCLA). The core problem is that unlike m-files that can be interrupted in mid-run using ctrl-c, MEX functions cannot be interrupted in the same way. Well, not officially, that is.<br />
Interrupts are very important for long-running user-facing operations. They can even benefit performance by avoiding the need to periodically poll some external state. Interrupts are registered asynchronously, and the program can query the interrupt buffer at its convenience, in special locations of its code, and/or at specific times depending on the required responsiveness.<br />
Yin reported that the <i>libut</i> library that ships with Matlab contain a large set of undocumented functions, including <code>utIsInterruptPending()</code> that can be used to detect ctrl-c interrupt events. The original report of this feature seems to be by Matlab old hand <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/37732#95811" rel="nofollow" target="_blank">Peter Boettcher back in 2002</a> (with a <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/326230" rel="nofollow" target="_blank">Fortran wrapper</a> reported in 2013). The importance of Yin&#8217;s post is that he clearly explained the use of this feature, with detailed coding and compilation instructions. Except for Peter&#8217;s original report, Yin&#8217;s post and the Fortran wrapper, precious few mentions can be found online (oddly enough, yours truly <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/247651#638201" rel="nofollow" target="_blank">mentioned it</a> in the very same CSSM newsletter post in which I outed this blog back in 2009). Apparently, this feature <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/37732" rel="nofollow" target="_blank">was supposed to have been made documented in R12.1</a>, but for some reason it was not and people just moved on and forgot about it.<br />
<span id="more-6454"></span><br />
The relevant functions seem to be:</p>
<pre lang="cpp">
// Most important functions (C):
bool utIsInterruptEnabled(void)
bool utIsInterruptPending(void)
bool utWasInterruptHandled(void)
bool utSetInterruptHandled(bool)
bool utSetInterruptEnabled(bool)
bool utSetInterruptPending(bool)
// Related functions (C, signature unknown):
? utHandlePendingInterrupt(?)
? utRestoreInterruptEnabled(?)
? utLongjmpIfInterruptPending(?)
// utInterruptMode class (C++):
utInterruptMode::utInterruptMode(enum utInterruptMode::Mode)  // constructor
utInterruptMode::~utInterruptMode(void)  // destructor
bool utInterruptMode::isInterruptEnabled(void)
enum utInterruptMode::Mode utInterruptMode::CurrentMode
enum utInterruptMode::Mode utInterruptMode::GetCurrentMode(void)
enum utInterruptMode::Mode utInterruptMode::GetOriginalMode(void)
enum utInterruptMode::Mode utInterruptMode::SetMode(enum utInterruptMode::Mode)
// utInterruptState class (C++):
class utInterruptState::AtomicPendingFlags utInterruptState::flags_pending
void utInterruptState::HandlePeekMsgPending(void)
bool utInterruptState::HandlePendingInterrupt(void)
bool utInterruptState::interrupt_handled
bool utInterruptState::IsInterruptPending(void)
bool utInterruptState::IsPauseMsgPending(void)
class utInterruptState & utInterruptState::operator=(class utInterruptState const &)
void utInterruptState::PeekMessageIfPending(void)
bool utInterruptState::SetInterruptHandled(bool)
bool utInterruptState::SetInterruptPending(bool)
bool utInterruptState::SetIqmInterruptPending(bool)
bool utInterruptState::SetPauseMsgPending(bool)
bool utInterruptState::SetPeekMsgPending(bool)
void utInterruptState::ThrowIfInterruptPending(void)
bool utInterruptState::WasInterruptHandled(void)
unsigned int const utInterruptState::FLAG_PENDING_CTRLC
unsigned int const utInterruptState::FLAG_PENDING_INTERRUPT_MASK
unsigned int const utInterruptState::FLAG_PENDING_IQM_INTERRUPT
unsigned int const utInterruptState::FLAG_PENDING_PAUSE
unsigned int const utInterruptState::FLAG_PENDING_PEEKMSG
</pre>
<p>Of all these functions, we can make do with just <code>utIsInterruptPending</code>, as <a href="http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick/" rel="nofollow" target="_blank">shown</a> by Yin (complete with compilation instructions):</p>
<pre lang="cpp">
/* A demo of Ctrl-C detection in mex-file by Wotao Yin. Jan 29, 2010. */
#include "mex.h"
#if defined (_WIN32)
    #include <windows.h>
#elif defined (__linux__)
    #include <unistd.h>
#endif
#ifdef __cplusplus
    extern "C" bool utIsInterruptPending();
#else
    extern bool utIsInterruptPending();
#endif
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int count = 0;
    while(1) {
        #if defined(_WIN32)
            Sleep(1000);        /* Sleep one second */
        #elif defined(__linux__)
            usleep(1000*1000);  /* Sleep one second */
        #endif
        mexPrintf("Count = %d\n", count++);  /* print count and increase it by 1 */
        mexEvalString("drawnow;");           /* flush screen output */
        if (utIsInterruptPending()) {        /* check for a Ctrl-C event */
            mexPrintf("Ctrl-C Detected. END\n\n");
            return;
        }
        if (count == 10) {
            mexPrintf("Count Reached 10. END\n\n");
            return;
        }
    }
}
</pre>
<p>After returning to Matlab, the Ctrl-C event will stop the execution of the caller function(s). However, sometimes we would like to keep the partial calculation, for example if the calculation can later be resumed from the point of interruption. It&#8217;s not possible to save partial result using only the utIsInterruptPending() function. However, it is possible to reset the interrupt state so that Matlab will not stop the execution after returning control from the mex function, and the caller function can get and use the partial calculation. The magic is done using another undocumented libut function named ​<i>utSetInterruptPending()</i>. A short example is included below (provided by Zvi Devir):</p>
<pre lang="cpp" highlight="4,14">
// Import libut functions
#pragma comment(lib, "libut.lib")
extern "C" bool utIsInterruptPending();
extern "C" bool utSetInterruptPending(bool);
// Run calculation divided into steps
int n;
for (n = 0; n < count; n++) {
	// some expensive calculation
	a_long_calculation(..., n);
	if (utIsInterruptPending()) {		// check for a Ctrl-C event
		mexPrintf("Ctrl-C detected [%d/%d].\n\n", n, count);
		utSetInterruptPending(false);	// Got it... consume event
		break;
	}
}
// Write back partial or full calculation
...
</pre>
<p>An elaboration of the idea of Ctrl-C detection was <a href="https://groups.google.com/d/msg/gerardus-users/m3rzaxHnmMM/eVo6K2WZxvYJ" rel="nofollow" target="_blank">created</a> by <a href="http://www.cs.ox.ac.uk/people/ramon.caserocanas/" rel="nofollow" target="_blank">Ramon Casero</a> (Oxford) for the <a href="https://github.com/rcasero/gerardus" rel="nofollow" target="_blank">Gerardus project</a>. Ramon wrapped Yin's code in C/C++ <code>#define</code> to create an easy-to-use pre-processor function <code>ctrlcCheckPoint(fileName,lineNumber)</code>:</p>
<pre lang="cpp">
...
ctrlcCheckPoint(__FILE__, __LINE__);  // exit if user pressed Ctrl+C
...
</pre>
<p>Here's the code for the preprocessor header file (<a href="https://github.com/rcasero/gerardus/blob/master/matlab/GerardusCommon.h" rel="nofollow" target="_blank"><i>GerardusCommon.h</i></a>) that #defines <code>ctrlcCheckPoint()</code> (naturally, the <code>__FILE__</code> and <code>__LINE__</code> parts could also be made part of the #define, for even simpler usage):</p>
<pre lang="cpp">
 /*
  * Author: Ramon Casero <rcasero@gmail.com>
  * Copyright © 2011-2013 University of Oxford
  * Version: 0.10.2
  *
  * University of Oxford means the Chancellor, Masters and Scholars of
  * the University of Oxford, having an administrative office at
  * Wellington Square, Oxford OX1 2JD, UK.
  *
  * This file is part of Gerardus.
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details. The offer of this
  * program under the terms of the License is subject to the License
  * being interpreted in accordance with English Law and subject to any
  * action against the University of Oxford being under the jurisdiction
  * of the English Courts.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see
  * <http://www.gnu.org/licenses/>.
  */
#ifndef GERARDUSCOMMON_H
#define GERARDUSCOMMON_H
/* mex headers */
#include <mex.h>
/* C++ headers */
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
/* ITK headers */
#include "itkOffset.h"
/*
 * utIsInterruptPending(): "undocumented MATLAB API implemented in
 * libut.so, libut.dll, and included in the import library
 * libut.lib. To use utIsInterruptPending in a mex-file, one must
 * manually declare bool utIsInterruptPending() because this function
 * is not included in any header files shipped with MATLAB. Since
 * libut.lib, by default, is not linked by mex, one must explicitly
 * tell mex to use libut.lib." -- Wotao Yin,
 * http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick/
 *
 */
#ifdef __cplusplus
    extern "C" bool utIsInterruptPending();
#else
    extern bool utIsInterruptPending();
#endif
/*
 * ctrlcCheckPoint(): function to check whether the user has pressed
 * Ctrl+C, and if so, terminate execution returning an error message
 * with a hyperlink to the offending function's help, and a hyperlink
 * to the line in the source code file this function was called from
 *
 * It is implemented as a C++ macro to check for the CTRL+C flag, and
 * a call to function ctrlcErrMsgTxt() inside, to throw the error. The
 * reason is that if ctrlcCheckPoint() were a function instead of a
 * macro, this would introduce a function call at every iteration of
 * the loop, which is very expensive. But then we don't want to put
 * the whole error message part inside a macro, it's bug-prone and bad
 * programming practice. And once the CTRL+C has been detected,
 * whether the error message is generated a bit faster or not is not
 * important.
 *
 * In practice, to use this function put a call like this e.g. inside
 * loops that may take for a very long time:
 *
 *    // exit if user pressed Ctrl+C
 *    ctrlcCheckPoint(__FILE__, __LINE__);
 *
 * sourceFile: full path and name of the C++ file that calls this
 *             function. This should usually be the preprocessor
 *             directive __FILE__
 *
 * lineNumber: line number where this function is called from. This
 *             should usually be the preprocessor directive __LINE__
 *
 */
inline
void ctrlcErrMsgTxt(std::string sourceFile, int lineNumber) {
  // run from here the following code in the Matlab side:
  //
  // >> path = mfilename('fullpath')
  //
  // this provides the full path and function name of the function
  // that called ctrlcCheckPoint()
  int nlhs = 1; // number of output arguments we expect
  mxArray *plhs[1]; // to store the output argument
  int nrhs = 1; // number of input arguments we are going to pass
  mxArray *prhs[1]; // to store the input argument we are going to pass
  prhs[0] = mxCreateString("fullpath"); // input argument to pass
  if (mexCallMATLAB(nlhs, plhs, nrhs, prhs, "mfilename")) { // run mfilename('fullpath')
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') returned error");
  }
  if (plhs == NULL) {
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') returned NULL array of outputs");
  }
  if (plhs[0] == NULL) {
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') returned NULL output instead of valid path");
  }
  // get full path to current function, including function's name
  // (without the file extension)
  char *pathAndName = mxArrayToString(plhs[0]);
  if (pathAndName == NULL) {
    mexErrMsgTxt("ctrlcCheckPoint(): mfilename('fullpath') output cannot be converted to string");
  }
  // for some reason, using mexErrMsgTxt() to give this output
  // doesn't work. Instead, we have to give the output to the
  // standar error, and then call mexErrMsgTxt() to terminate
  // execution of the program
  std::cerr << "Operation terminated by user during "
	    << "<a href=\"matlab:helpUtils.errorDocCallback('"
	    << mexFunctionName()
	    << "', '" << pathAndName << ".m', " << lineNumber << ")\">"
	    << mexFunctionName()
	    << "</a> (<a href=\"matlab:opentoline('"
	    << sourceFile
	    << "'," << lineNumber << ",0)\">line " << lineNumber
	    << "</a>)"
	    << std::endl;
  mexErrMsgTxt("");
}
#define ctrlcCheckPoint(sourceFile, lineNumber)		\
  if (utIsInterruptPending()) {				\
    ctrlcErrMsgTxt(sourceFile, lineNumber);		\
  }
</pre>
<p>This feature has remained as-is since at least 2002 (when Peter first reported it), and apparently works to this day. Why then did I categorize this as "High risk for breaking in a future Matlab versions"? The reason is that internal undocumented MEX functions are prone to break in new Matlab releases (<a href="/articles/serializing-deserializing-matlab-data" target="_blank">example</a>). Hopefully my report today will prompt MathWorks to make this feature documented, rather than to remove it from a future release 🙂<br />
By the way, if anyone knows any use for the other interrupt-related functions in <i>libut</i> that I listed above, and/or the missing signatures, please leave a note below and I will update here accordingly.<br />
<b><u>Addendum July 2, 2016:</u></b> Pavel Holoborodko <a href="http://www.advanpix.com/2016/07/02/devnotes-3-proper-handling-of-ctrl-c-in-mex-module" rel="nofollow" target="_blank">just posted</a> an asynchronous version of this mechanism, which is an improvement of the synchronous code above. Pavel uses a separate Windows thread to check the Ctrl-C interrupt state. Readers can extend this idea to use threads for other asynchronous (multi-threaded) computations or I/O. In chapter 7 of my book "<a href="/books/matlab-java" rel="nofollow" target="_blank">Accelerating MATLAB Performance</a>" I explain how we can use Posix threads (pthreads) or OpenMP threads for similar multithreading in MEX (unlike Windows threads, pthreads and OpenMP are cross platform). Users can also use other multithreading solutions, such as the open-source Boost library (bundled with Matlab) or Intel's commercial TBB.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt">MEX ctrl-c interrupt</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/faster-csvwrite-dlmwrite" rel="bookmark" title="Faster csvwrite/dlmwrite">Faster csvwrite/dlmwrite </a> <small>The speed of the builtin csvwrite, dlmwrite functions can be improved dramatically. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-list" rel="bookmark" title="Undocumented feature list">Undocumented feature list </a> <small>A list of undocumented MATLAB features can be retrieved. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api" rel="bookmark" title="Undocumented Matlab MEX API">Undocumented Matlab MEX API </a> <small>Matlab's MEX API contains numerous undocumented functions, that can be extremely useful. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data" rel="bookmark" title="Serializing/deserializing Matlab data">Serializing/deserializing Matlab data </a> <small>Matlab does not provide a documented manner to serialize data into a byte stream, but we can do this with some undocumented functionality. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/mex-ctrl-c-interrupt/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Better MEX error messages</title>
		<link>https://undocumentedmatlab.com/articles/better-mex-error-messages?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=better-mex-error-messages</link>
					<comments>https://undocumentedmatlab.com/articles/better-mex-error-messages#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 24 Feb 2016 18:00:25 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pavel Holoborodko]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6287</guid>

					<description><![CDATA[<p>The default clunky and release-incompatible MEX error messages can be improved using a simple hack. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/better-mex-error-messages">Better MEX error messages</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex" rel="bookmark" title="Checking status of warning messages in MEX">Checking status of warning messages in MEX </a> <small>Undocumented Mex functions can be used to extract the state of Matlab warnings in run-time. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-system-tray-popup-messages" rel="bookmark" title="Setting system tray popup messages">Setting system tray popup messages </a> <small>System-tray icons and messages can be programmatically set and controlled from within Matlab, using new functionality available since R2007b....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/sending-email-text-messages-from-matlab" rel="bookmark" title="Sending email/text messages from Matlab">Sending email/text messages from Matlab </a> <small>Sending emails and SMS (text) messages from Matlab is easy, once you know a few quirks....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2" rel="bookmark" title="Matlab compilation quirks &#8211; take 2">Matlab compilation quirks &#8211; take 2 </a> <small>A few hard-to-trace quirks with Matlab compiler outputs are explained. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to introduce guest blogger Pavel Holoborodko, the developer of the <a href="http://advanpix.com" target="_blank">Advanpix Multiprecision Computing Toolbox for MATLAB</a>. Pavel has already posted here in the past as a guest blogger about <a href="/articles/undocumented-matlab-mex-api" target="_blank">undocumented Matlab MEX functions</a>. Today he will discuss another little-known aspect of advanced MEX programming with Matlab.</i><br />
MEX API provides two functions for proper handling of erroneous situations: the legacy <a href="http://mathworks.com/help/matlab/apiref/mexerrmsgtxt.html" rel="nofollow" target="_blank"><code>mexErrMsgTxt</code></a> and the newer <a href="http://mathworks.com/help/matlab/apiref/mexerrmsgidandtxt.html" rel="nofollow" target="_blank"><code>mexErrMsgIdAndTxt</code></a>. Both show error message, interrupt execution of a MEX module and return control to Matlab immediately.<br />
Under the hood, these functions are implemented through C++ exceptions. The reason for this design choice is unclear. Throwing C++ exceptions across module boundary (e.g. from dynamic library to host process) is unsafe and generally considered as bad practice in software design. Exceptions are part of C++ run-time library and different versions of it might have incompatible implementations.<br />
This restricts MEX to use only the same version of C++ run-time and GCC which were used to build that particular version of Matlab itself. This is one of the reasons why TMW distributes its own version of GCC/libstdc++ along with every release of Matlab and pushes developers to use it for MEX compilation.<br />
Such unfortunate design decision have two unpleasant consequences:</p>
<ol>
<li>developers must use some old version of GCC (forget all the fancy stuff from C++11, C++14, etc.)</li>
<li>compiled MEX modules most likely will not work on older/newer versions of MATLAB (re-compilation is required).</li>
</ol>
<p>The good news is that both issues are solvable and I will write more about this in the future (it is actually possible to create single binary MEX module, which will work on any GNU Linux flavor regardless of the versions of libc/libstc++/gcc installed in the system or used in Matlab).<br />
Here I propose just first step towards freedom – avoid direct usage of <code>mexErrMsg**</code> functions. Use a simple wrapper instead:</p>
<pre lang="c">
void mxShowCriticalErrorMessage(const char *msg)
{
    mxArray *arg;
    arg = mxCreateString(msg);
    mexCallMATLAB(0,0,1,&arg,"error");
}
</pre>
<p><span id="more-6287"></span><br />
The <code>mxShowCriticalErrorMessage</code> function calls Matlab&#8217;s built-in <i><b>error</b></i> function via the interpreter, with the error message as input parameter.<br />
In addition to being safe, this approach potentially gives us better control over what additional information is shown together with error messages. Instead of a string, we can use an <code>errorStruct</code> as input argument to Matlab&#8217;s <i><b>error</b></i> function, with its fields tuned to our requirements (not shown here as I want to keep the example simple).<br />
Even without tuning, output of <code>mxShowCriticalErrorMessage</code> is much more informative and user-friendly:</p>
<ul>
<li><b>Error message from Matlab&#8217;s built-in functionality:</b><br />
</p>
<div class="wp_syntax" style="margin-bottom: 10px;">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; A = <span style="color: #0000FF;">magic</span><span style="color: #080;">(</span><span style="color: #33f;">3</span><span style="color: #080;">)</span>;
&gt;&gt; A<span style="color: #080;">(</span><span style="color: #33f;">0</span><span style="color: #080;">)</span>
<span style="color: #F00;">Subscript indices must either be real positive integers or logicals.</span></pre>
</div>
</div>
<p>Nice one-line message without any distracting information.<br />
&nbsp;</li>
<li><b>Error message from MEX using <code>mexErrMsgTxt</code>/<code>mexErrMsgIdAndTxt</code>:</b><br />
</p>
<div class="wp_syntax" style="margin-bottom: 10px;">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; A = mp<span style="color: #080;">(</span><span style="color: #0000FF;">magic</span><span style="color: #080;">(</span><span style="color: #33f;">3</span><span style="color: #080;">)</span><span style="color: #080;">)</span>;   <span style="color: #228B22;">% convert matrix to arbitrary precision type, provided by our toolbox</span>
&gt;&gt; A<span style="color: #080;">(</span><span style="color: #33f;">0</span><span style="color: #080;">)</span>                <span style="color: #228B22;">% subsref is called from toolbox, it is implemented in mpimpl.mex</span>
<span style="color: #F00;">Error using mpimpl
Subscript indices must either be real positive integers or logicals.
Error in mp/subsref (line 860)
        [varargout{1:nargout}] = mpimpl(170, varargin{:});</span></pre>
</div>
</div>
<p>Intimidating four lines with actual error message lost in the middle. All the additional information is meaningless for end-user and actually misleading.<br />
The worst thing is that such error message is very different from what user get used to (see above one-liner), which leads to confusion if MEX plugin is properly working at all.<br />
&nbsp;</li>
<li><b>Error message from MEX using <code>mxShowCriticalErrorMessage</code>:</b><br />
</p>
<div class="wp_syntax" style="margin-bottom: 10px;">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; A = <span style="color: #0000FF;">magic</span><span style="color: #080;">(</span><span style="color: #33f;">3</span><span style="color: #080;">)</span>;
&gt;&gt; A<span style="color: #080;">(</span><span style="color: #33f;">0</span><span style="color: #080;">)</span>
<span style="color: #F00;">Error using mp/subsref (line 860)
Subscript indices must either be real positive integers or logicals.</span></pre>
</div>
</div>
<p>Now the message is clear and short, with error description in the last line where the user focus is.<br />
&nbsp;</li>
</ul>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/better-mex-error-messages">Better MEX error messages</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex" rel="bookmark" title="Checking status of warning messages in MEX">Checking status of warning messages in MEX </a> <small>Undocumented Mex functions can be used to extract the state of Matlab warnings in run-time. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-system-tray-popup-messages" rel="bookmark" title="Setting system tray popup messages">Setting system tray popup messages </a> <small>System-tray icons and messages can be programmatically set and controlled from within Matlab, using new functionality available since R2007b....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/sending-email-text-messages-from-matlab" rel="bookmark" title="Sending email/text messages from Matlab">Sending email/text messages from Matlab </a> <small>Sending emails and SMS (text) messages from Matlab is easy, once you know a few quirks....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2" rel="bookmark" title="Matlab compilation quirks &#8211; take 2">Matlab compilation quirks &#8211; take 2 </a> <small>A few hard-to-trace quirks with Matlab compiler outputs are explained. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/better-mex-error-messages/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented feature list</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-feature-list?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-feature-list</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-feature-list#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 19 Mar 2014 18:00:30 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4724</guid>

					<description><![CDATA[<p>A list of undocumented MATLAB features can be retrieved. Here's how... </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-feature-list">Undocumented feature list</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-function" rel="bookmark" title="Undocumented feature() function">Undocumented feature() function </a> <small>Matlab's undocumented feature function enables access to some internal experimental features...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/the-hotlinks-feature" rel="bookmark" title="The HotLinks feature">The HotLinks feature </a> <small>feature('HotLinks') can be used to temporarily disable hyperlinks and other markups in the Matlab console. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/legend-semi-documented-feature" rel="bookmark" title="Legend &#039;-DynamicLegend&#039; semi-documented feature">Legend &#039;-DynamicLegend&#039; semi-documented feature </a> <small>The built-in Matlab legend function has a very useful semi-documented feature for automatic dynamic update, which is explained here....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Three years ago I posted an article on <a target="_blank" href="/articles/undocumented-feature-function/">Matlab&#8217;s undocumented <i><b>feature</b></i> function</a>. <i><b>feature</b></i> is a Matlab function that enables access to undocumented internal Matlab functionality. Most of this functionality is not very useful, but in some cases it could indeed be very interesting. As sometimes happens, this innocent-enough article generated a lot of interest, both online and offline. Perhaps the reason was that in this article I listed the known list of supported features with a short explanation and references were available. At the time, this was the only comprehensive such listing, which I manually collected from numerous sources. For this reason I was delighted to receive Yves Piguet&#8217;s <a target="_blank" href="/articles/undocumented-feature-function/#comment-34109">tip</a> about the availability of a programmatic interface for a full listing of features:</p>
<pre lang='matlab'>
>> list = feature('list')   % 260 features in R2013b
list =
1x260 struct array with fields:
    name
    value
    has_callback
    has_builtin
    call_count
</pre>
<p>Which can be listed as follows:</p>
<pre lang='matlab'>
for i = 1 : length(list)
   fprintf('%35s has_cb=%d has_bi=%d calls=%d val=%g\n', ...
      list(i).name, list(i).has_callback, list(i).has_builtin, list(i).call_count, list(i).value);
end
                    100 has_cb=0 has_bi=1 calls=0 val=1
                    102 has_cb=0 has_bi=1 calls=0 val=1
                     12 has_cb=0 has_bi=1 calls=0 val=1
                     14 has_cb=0 has_bi=1 calls=0 val=1
                     25 has_cb=0 has_bi=1 calls=0 val=1
                    300 has_cb=0 has_bi=0 calls=0 val=1
                    301 has_cb=0 has_bi=0 calls=0 val=1
                     44 has_cb=0 has_bi=1 calls=0 val=1
                     45 has_cb=0 has_bi=1 calls=0 val=1
                      7 has_cb=0 has_bi=0 calls=0 val=1
                      8 has_cb=0 has_bi=1 calls=0 val=1
                      9 has_cb=0 has_bi=0 calls=0 val=1
                  accel has_cb=0 has_bi=1 calls=0 val=0
         AccelBlockSize has_cb=0 has_bi=1 calls=0 val=0
          AccelMaxTemps has_cb=0 has_bi=1 calls=0 val=0
    AccelThreadBlockMin has_cb=0 has_bi=1 calls=0 val=0
              allCycles has_cb=0 has_bi=1 calls=0 val=0
 AllWarningsCanBeErrors has_cb=1 has_bi=0 calls=0 val=0
           ArrayEditing has_cb=0 has_bi=0 calls=0 val=1
       AutomationServer has_cb=0 has_bi=1 calls=0 val=0
              CachePath has_cb=0 has_bi=0 calls=0 val=1
     CaptureScreenCount has_cb=0 has_bi=0 calls=0 val=0
       CheckMallocClear has_cb=0 has_bi=0 calls=0 val=1
                    ... (etc. etc.)
</pre>
<p>Unfortunately, in the latest Matlab R2014a, which was released last week, this nice feature has been removed:</p>
<pre lang='matlab'>
>> list = feature('list')
Error using feature
Feature list not found
</pre>
<p>Luckily, the list can still be retrieved programmatically, using an undocumented MEX library function. Place the following in a file called <i>feature_list.cpp</i>:<br />
<span id="more-4724"></span></p>
<pre lang='c'>
#include "mex.h"
void svListFeatures(int, mxArray_tag** const, int, mxArray_tag** const);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    svListFeatures(1,plhs,0,NULL);
}
</pre>
<p>Now compile this MEX file:</p>
<pre lang='matlab'>
if isunix
   mex('feature_list.cpp',['-L',matlabroot,'/bin/',computer('arch')],'-lmwservices');
else
   mex('feature_list.cpp','-llibmwservices');
end
</pre>
<p>As you can see, all this MEX function does is just call the <i>svListFeatures()</i> function from the <i>libmwservices</i> dynamic/shared library.<br />
We can now run this MEX function directly in Matlab:</p>
<pre lang='matlab'>
>> list = feature_list
list =
1x273 struct array with fields:
    name
    value
    has_callback
    has_builtin
    call_count
</pre>
<p>Running both the new <i><b>feature_list</b></i> and the previous <i><b>feature</b>(&#8216;list&#8217;)</i> on previous Matlab releases produces exactly the same result, showing that under the hood, <i><b>feature</b>(&#8216;list&#8217;)</i> was basically just calling <i>libmwservices</i>&#8216;s <i>svListFeatures()</i> function.<br />
There are 273 undocumented features in R2014a: 20 were added and 7 were removed compared to R2013b. For those interested, the modified features in the past two releases are:</p>
<ul>
<li>R2013b:
<ol>
<li>ConvertAllDoublesToHandles (added)</li>
<li>DrawnowNowaitFeature (added)</li>
<li>getsimd (added)</li>
<li>CoreDump (removed)</li>
</ol>
</li>
<li>R2014a:
<ol>
<li>GPUAllowPartialSharedDataCopies (added)</li>
<li>GPUAllowSharedDataCopies (added)</li>
<li>GetOpenGLData (added)</li>
<li>GetOpenGLInfo (added)</li>
<li>HGUpdateErrorChecking (added)</li>
<li>JVMShutdown (added)</li>
<li>LoadHG1FigFileWithHG1Defaults (added)</li>
<li>OpenGLBitmapZbufferBug (added)</li>
<li>OpenGLClippedImageBug (added)</li>
<li>OpenGLDockingBug (added)</li>
<li>OpenGLEraseModeBug (added)</li>
<li>OpenGLLineSmoothingBug (added)</li>
<li>OpenGLPolygonOffsetBiasBug (added)</li>
<li>OpenGLVerbose (added)</li>
<li>OpenGLWobbleTesselatorBug (added)</li>
<li>SaveFigFileWithHG1Defaults (added)</li>
<li>ShutdownReportLevel (added)</li>
<li>UseGenericOpenGL (added)</li>
<li>crash_mode (added)</li>
<li>isLightweightEval (added)</li>
<li>EnableBangErrors (removed)</li>
<li>EnableJavaAsGObject (removed)</li>
<li>List (removed) &#8211; this is actually the reason for today&#8217;s article!</li>
<li>hwtic (removed)</li>
<li>hwtoc (removed)</li>
<li>oldtictoc (removed)</li>
<li>timing (removed)</li>
</ol>
</li>
</ul>
<p>Happy digging!</p>
<div id="Packt">p.s. &#8211; Packt publishing, which publishes IT books, has a great deal on ebooks until March 26 &#8211; <a target="_blank" rel="nofollow" href="http://bit.ly/1j26nPN">buy 1 get 1 free</a>. Some of their books are Matlab-related. Check it out!</div>
<p><span id="R2015a"></span><br />
<b><u>Addendum July 18, 2016</u></b>: Since R2015a, <i><b>feature</b>(&#8216;list&#8217;)</i> returns an empty array. A reader of this blog, Mikhail P, reported the following workaround, by temporarily setting the <code>MWE_INSTALL</code> environment variable (that should then be reset, since it is used in other locations too):</p>
<pre lang="matlab">
% The following was run in R2016b
>> setenv('MWE_INSTALL','1'); list = feature('list'), setenv('MWE_INSTALL');
list =
  1×266 struct array with fields:
    name
    value
    has_callback
    has_builtin
    call_count
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-feature-list">Undocumented feature list</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-function" rel="bookmark" title="Undocumented feature() function">Undocumented feature() function </a> <small>Matlab's undocumented feature function enables access to some internal experimental features...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/the-hotlinks-feature" rel="bookmark" title="The HotLinks feature">The HotLinks feature </a> <small>feature('HotLinks') can be used to temporarily disable hyperlinks and other markups in the Matlab console. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/legend-semi-documented-feature" rel="bookmark" title="Legend &#039;-DynamicLegend&#039; semi-documented feature">Legend &#039;-DynamicLegend&#039; semi-documented feature </a> <small>The built-in Matlab legend function has a very useful semi-documented feature for automatic dynamic update, which is explained here....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-feature-list/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Explicit multi-threading in Matlab part 3</title>
		<link>https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=explicit-multi-threading-in-matlab-part3</link>
					<comments>https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 05 Mar 2014 18:00:26 +0000</pubDate>
				<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4686</guid>

					<description><![CDATA[<p>Matlab performance can be improved by employing POSIX threads in C/C++ code. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3">Explicit multi-threading in Matlab part 3</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part2" rel="bookmark" title="Explicit multi-threading in Matlab part 2">Explicit multi-threading in Matlab part 2 </a> <small>Matlab performance can be improved by employing .Net (C#, VB, F# or C++) threads. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part1" rel="bookmark" title="Explicit multi-threading in Matlab part 1">Explicit multi-threading in Matlab part 1 </a> <small>Explicit multi-threading can be achieved in Matlab by a variety of simple means. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part4" rel="bookmark" title="Explicit multi-threading in Matlab part 4">Explicit multi-threading in Matlab part 4 </a> <small>Matlab performance can be improved by employing timer objects and spawning external processes. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-threaded-mex" rel="bookmark" title="Multi-threaded Mex">Multi-threaded Mex </a> <small>Tips for creating and debugging multi-threaded Mex functions are discussed. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In the past weeks, I explained how we can start asynchronous Java threads to run in parallel to the main Matlab processing using <a target="_blank" href="/articles/explicit-multi-threading-in-matlab-part1/">Java</a> and <a target="_blank" href="/articles/explicit-multi-threading-in-matlab-part2/">Dot-Net</a> threads. Today I continue by examining C/C++ threads. This series will conclude next week, by discussing timer objects and process-spawning.<br />
The alternatives that can be used to enable Matlab multithreading with C/C++ include standard POSIX threads, native OS threads, OpenMP, MPI (Message Passing Interface), TBB (Thread Building Blocks), Cilk, OpenACC, OpenCL or Boost. We can also use libraries targeting specific platforms/architectures: Intel MKL, C++ AMP, Bolt etc. Note that the Boost library is included in every relatively-modern Matlab release, so we can either use the built-in library (easier to deploy, consistency with Matlab), or download and install the latest version and use it separately. On Windows, we can also use .Net&#8217;s <code>Thread</code> class, as explained in last week&#8217;s article. This is a very wide range of alternatives, and it&#8217;s already been covered extensively elsewhere from the C/C++ side.<br />
Today I will only discuss the POSIX alternative. The benefit of POSIX is that is is more-or-less cross-platform, enabling the same code to work on all MATLAB platforms, as well as any other POSIX-supported platform.<br />
<a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/POSIX_Threads">POSIX threads</a> (Pthreads) is a standard API for multi-threaded programming implemented natively on many Unix-like systems, and also supported on Windows. Pthreads includes functionality for creating and managing threads, and provides a set of synchronization primitives such as mutexes, conditional variables, semaphores, read/write locks, and barriers. POSIX has extensive offline and online <a target="_blank" rel="nofollow" href="http://tutorialspoint.com/cplusplus/cpp_multithreading.htm">documentation</a>.<br />
Note that POSIX is natively supported on Macs &#038; Linux, but requires a <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/POSIX_Threads#POSIX_Threads_for_Windows">separate installation on Windows</a>. Two of the leading alternatives are <a target="_blank" rel="nofollow" href="http://sourceware.org/pthreads-win32/">Pthreads_Win32</a> (also works on Win64, despite its name&#8230;), and winpthreads (part of the extensive <a target="_blank" rel="nofollow" href="http://mingw-w64.sourceforge.net">MinGW</a> open-source project).<br />
When creating a C/C++ -based function, we can either compile/link it into a dynamic/shared library (loadable into Matlab using the <i><b>loadlibrary</b></i> &#038; <i><b>calllib</b></i> functions), or into a MEX file that can be called directly from M-code. The code looks the same, except that a MEX file has a gateway function named <i>mexFunction</i> that has a predefined interface. Today I&#8217;ll show the MEX variant using C; the adaptation to C++ is easy. To create multi-threaded MEX, all it takes is to connect the thread-enabled C/C++ code into our <i>mexFunction()</i>, provide the relevant threading library to the <i><b>mex</b></i> linker and we&#8217;re done.<br />
<span id="more-4686"></span><br />
The example code below continues the I/O example used throughout this series, of asynchronously saving a vector of data to disk file. Place the following in a file called <i>myPosixThread.c</i>:</p>
<pre lang='csharp'>
#include "mex.h"
#include "pthread.h"
#include "stdio.h"
char *filename;
double *data;
size_t numElementsExpected;
size_t numElementsWritten;
/* thread compute function */
void *thread_run(void *p)
{
    /* Open the file for binary output */
    FILE *fp = fopen(filename, "wb");
    if (fp == NULL)
        mexErrMsgIdAndTxt("YMA:MexIO:errorOpeningFile", "Could not open file %s", filename);
    /* Write the data to file */
    numElementsWritten = (size_t) fwrite(data, sizeof(double), numElementsExpected, fp);
    fclose(fp);
    /* Ensure that the data was correctly written */
    if (numElementsWritten != numElementsExpected)
        mexErrMsgIdAndTxt("YMA:MexIO:errorWritingFile",
                "Error writing data to %s: wrote %d, expected %d\n",
                filename, numElementsWritten, numElementsExpected);
    /* Cleanup */
    pthread_exit(NULL);
}
/* The MEX gateway function */
void mexFunction(int nlhs,       mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    pthread_t thread;
    /* Check for proper number of input and output arguments */
    if (nrhs != 2)
        mexErrMsgIdAndTxt("YMA:MexIO:invalidNumInputs", "2 input args required: filename, data");
    if (nlhs > 0)
        mexErrMsgIdAndTxt("YMA:MexIO:maxlhs", "Too many output arguments");
    if (!mxIsChar(prhs[0]))
        mexErrMsgIdAndTxt("YMA:MexIO:invalidInput", "Input filename must be of type string");
    if (!mxIsDouble(prhs[1]))
        mexErrMsgIdAndTxt("YMA:MexIO:invalidInput", "Input data must be of type double");
    /* Get the inputs: filename & data */
    filename = mxArrayToString(prhs[0]);
    data = mxGetPr(prhs[1]);
    numElementsExpected = mxGetNumberOfElements(prhs[1]);
    /* Launch a new I/O thread using default attributes */
    if (pthread_create(&thread, NULL, thread_run, NULL))
        mexErrMsgIdAndTxt("YMA:MexIO:threadFailed", "Thread creation failed");
}
</pre>
<p>This source file can be compiled as follows on Macs/Linux:</p>
<pre lang='matlab'>mex myPosixThread.c –lpthread</pre>
<p>Or on Windows, assuming we installed Pthreads-Win32, we need to <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/19467455/how-to-set-up-pthreads-on-windows">set-up the environment</a>:</p>
<pre lang='matlab'>
% prepare the environment (we could also use the -I, -L flags)
pthreadsInstallFolder = 'C:\Program Files\Pthreads_Win32\';  % change this as needed
setenv('PATH',   [getenv('PATH')    ';' pthreadsInstallFolder 'dll\x64']);
setenv('LIB',    [getenv('LIB')     ';' pthreadsInstallFolder 'lib\x64']);
setenv('INCLUDE',[getenv('INCLUDE') ';' pthreadsInstallFolder 'include']);
% create a 64-bit MEX that uses the pthreads DLL
mex myPosixThread.c -lpthreadVC2
% copy the pthreadVC2.dll file to be accessible to the MEX file, otherwise it will not run
copyfile([pthreadsInstallFolder 'dll\x64\pthreadVC2.dll'], '.')
</pre>
<p>To run the MEX file from MATLAB, we use the following code snippet (note the similarity with our Java/.Net examples earlier in this series):</p>
<pre lang='matlab'>
addpath('C:\Yair\Code\');  % location of our myPosixThread MEX file
data = rand(5e6,1);  % pre-processing (5M elements, ~40MB)
myPosixThread('F:\test.data',data);  % start running in parallel
data2 = fft(data);  % post-processing (pthread I/O runs in parallel)
</pre>
<p>Note that we cannot directly modify the data (<code>data=fft(data)</code>) while it is being accessed by the I/O thread. This would cause the data to be reallocated elsewhere in memory, causing the I/O thread to access invalid (stale) memory &#8211; this would cause a segmentation violation causing Matlab to crash. Read-only access (<code>data2=fft(data)</code>) is ok, just ensure not to update the data. This was not a problem with our earlier Java/.Net threads, since they received their data <i>by value</i>, but <i>mexFunction()</i> receives its data <i>by reference</i> (which is quicker and saves memory, but also has its limitations). Alternatively, we can <i>memcpy()</i> the Matlab data to a newly-allocated memory block within our thread and only use the <i>memcpy</i>&#8216;ed data from then on. This will ensure that if any updates to the original data occur, the parallel thread will not be affected and no SEGV will occur.<br />
Also note that we call a few MEX functions from within the parallel portion of our code (the thread&#8217;s <i>run()</i> function). This works without problems on recent Matlab releases since some MEX API functions have been made thread-safe, however it might not work in earlier (or future) Matlab versions. Therefore, to make our code portable, it is recommended to not interact with Matlab at all during parallel blocks, or to protect MEX API calls by critical sections. Alternatively, only use MEX API calls in the main thread (which is actually MT), defined as those parts of code that run in the same thread as <i>mexFunction()</i>. Synchronization with other threads can be done using POSIX mechanisms such as <i>pthread_join()</i>.<br />
To complete the picture, it is also possible to use <a target="_blank" rel="nofollow" href="http://www.instructables.com/id/Matlab-Multithreading-EASY/">native threads</a> (rather than POSIX) on Windows: The MEX file should <code>#include &lt;process.h></code> and call <i>_beginthread()</i>. In fact, since Microsoft for some reason decided to reinvent the wheel with its own native threads and not to support POSIX, all the POSIX implementations on Windows are basically a wrapper for the native Window threads. Using these native threads directly often proves to be the fastest alternative. Unfortunately, code using native threads is not portable to Macs/Linux, unlike POSIX-based code.<br />
Yuval Tassa&#8217;s excellent <a target="_blank" rel="nofollow" href="http://mathworks.com/matlabcentral/fileexchange/37515-mmx-multithreaded-matrix-operations-on-n-d-matrices">mmx utility</a> (which deserves a detailed review by its own right!) employs both Pthreads (Mac/Linux) and Windows threads in its MEX file. Readers are encouraged to review mmx&#8217;s code to see the specifics.<br />
Another related utility on the Matlab File Exchange is Thomas Weibel&#8217;s <a target="_blank" rel="nofollow" href="http://mathworks.com/matlabcentral/fileexchange/38034-mexthread">MexThread</a>, which uses <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/C%2B%2B11">C++11</a>&#8216;s <a target="_blank" rel="nofollow" href="http://en.cppreference.com/w/cpp/thread/thread"><code>std::threads</code></a>.<br />
<u><b>Addendum 2018-07-18</b></u>: A followup post about <a href="https://undocumentedmatlab.com/articles/multi-threaded-mex" target="_blank">creating and debugging multi-threaded C-based MEX functions</a> was just posted.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3">Explicit multi-threading in Matlab part 3</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part2" rel="bookmark" title="Explicit multi-threading in Matlab part 2">Explicit multi-threading in Matlab part 2 </a> <small>Matlab performance can be improved by employing .Net (C#, VB, F# or C++) threads. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part1" rel="bookmark" title="Explicit multi-threading in Matlab part 1">Explicit multi-threading in Matlab part 1 </a> <small>Explicit multi-threading can be achieved in Matlab by a variety of simple means. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part4" rel="bookmark" title="Explicit multi-threading in Matlab part 4">Explicit multi-threading in Matlab part 4 </a> <small>Matlab performance can be improved by employing timer objects and spawning external processes. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-threaded-mex" rel="bookmark" title="Multi-threaded Mex">Multi-threaded Mex </a> <small>Tips for creating and debugging multi-threaded Mex functions are discussed. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Serializing/deserializing Matlab data</title>
		<link>https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=serializing-deserializing-matlab-data</link>
					<comments>https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 22 Jan 2014 19:57:49 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4583</guid>

					<description><![CDATA[<p>Matlab does not provide a documented manner to serialize data into a byte stream, but we can do this with some undocumented functionality. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data">Serializing/deserializing Matlab data</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/inter-matlab-data-transfer-with-memcached" rel="bookmark" title="Inter-Matlab data transfer with memcached">Inter-Matlab data transfer with memcached </a> <small>The memcached library can be used to transfer data between separate Matlab processes (sessions). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-mex-in-place-editing" rel="bookmark" title="Matlab mex in-place editing">Matlab mex in-place editing </a> <small>Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/draggable-plot-data-tips" rel="bookmark" title="Draggable plot data-tips">Draggable plot data-tips </a> <small>Matlab's standard plot data-tips can be customized to enable dragging, without being limitted to be adjacent to their data-point. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last year I wrote an article on improving the <a target="_blank" href="/articles/improving-save-performance/">performance of the <i><b>save</b></i> function</a>. The article discussed various ways by which we can store Matlab data on disk. However, in many cases we are interested in a byte-stream serialization, in order to transmit information to external processes.<br />
<span class="alignright"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/serial2.jpg" width="230" height="280" /></span> The request to get a serialized byte-stream of Matlab data has been around for many years (<a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/4807035/is-it-possible-to-intercept-a-matlab-save-bytestream">example</a>), but MathWorks has never released a documented way of serializing and unserializing data, except by storing onto a disk file and later loading it from file. Naturally, using a disk file significantly degrades performance. We could always use a RAM-disk or flash memory for improved performance, but in any case this seems like a major overkill to such a simple requirement.<br />
In last year&#8217;s article, I presented a <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/fileexchange/34564-fast-serialize-deserialize">File Exchange utility</a> for such generic serialization/deserialization. However, that utility is limited in the types of data that it supports, and while it is relatively fast, there is a much better, more generic and faster solution.<br />
The solution appears to use the undocumented built-in functions <i><b>getByteStreamFromArray</b></i> and <i><b>getArrayFromByteStream</b></i>, which are apparently used internally by the <i><b>save</b></i> and <i><b>load</b></i> functions. The usage is very simple:</p>
<pre lang='matlab'>
byteStream = getByteStreamFromArray(anyData);  % 1xN uint8 array
anyData = getArrayFromByteStream(byteStream);
</pre>
<p>Many Matlab functions, documented and undocumented alike, are defined in XML files within the <i>%matlabroot%/bin/registry/</i> folder; our specific functions can be found in <i>%matlabroot%/bin/registry/hgbuiltins.xml</i>. While other functions include information about their location and number of input/output args, these functions do not. Their only XML attribute is <code>type = ":all:"</code>, which seems to indicate that they accept all data types as input. Despite the fact that the functions are defined in <i>hgbuiltins.xml</i>, they are <b>not</b> limited to HG objects &#8211; we can serialize basically any Matlab data: structs, class objects, numeric/cell arrays, sparse data, Java handles, timers, etc. For example:<br />
<span id="more-4583"></span></p>
<pre lang='matlab'>
% Simple Matlab data
>> byteStream = getByteStreamFromArray(pi)  % 1x72 uint8 array
byteStream =
  Columns 1 through 19
    0    1   73   77    0    0    0    0   14    0    0    0   56    0    0    0    6    0    0
  Columns 20 through 38
    0    8    0    0    0    6    0    0    0    0    0    0    0    5    0    0    0    8    0
  Columns 39 through 57
    0    0    1    0    0    0    1    0    0    0    1    0    0    0    0    0    0    0    9
  Columns 58 through 72
    0    0    0    8    0    0    0   24   45   68   84  251   33    9   64
>> getArrayFromByteStream(byteStream)
ans =
          3.14159265358979
% A cell array of several data types
>> byteStream = getByteStreamFromArray({pi, 'abc', struct('a',5)});  % 1x312 uint8 array
>> getArrayFromByteStream(byteStream)
ans =
    [3.14159265358979]    'abc'    [1x1 struct]
% A Java object
>> byteStream = getByteStreamFromArray(java.awt.Color.red);  % 1x408 uint8 array
>> getArrayFromByteStream(byteStream)
ans =
java.awt.Color[r=255,g=0,b=0]
% A Matlab timer
>> byteStream = getByteStreamFromArray(timer);  % 1x2160 uint8 array
>> getArrayFromByteStream(byteStream)
   Timer Object: timer-2
   Timer Settings
      ExecutionMode: singleShot
             Period: 1
           BusyMode: drop
            Running: off
   Callbacks
           TimerFcn: ''
           ErrorFcn: ''
           StartFcn: ''
            StopFcn: ''
% A Matlab class object
>> byteStream = getByteStreamFromArray(matlab.System);  % 1x1760 uint8 array
>> getArrayFromByteStream(byteStream)
ans =
  System: matlab.System
</pre>
<h3 id="HG">Serializing HG objects</h3>
<p>Of course, we can also serialize/deserialize also HG controls, plots/axes and even entire figures. When doing so, it is important to serialize the <i><b>handle</b></i> of the object, rather than its numeric handle, since we are interested in serializing the graphic object, not the scalar numeric value of the handle:</p>
<pre lang='matlab'>
% Serializing a simple figure with toolbar and menubar takes almost 0.5 MB !
>> hFig = handle(figure);  % a new default Matlab figure
>> length(getByteStreamFromArray(hFig))
ans =
      479128
% Removing the menubar and toolbar removes much of this amount:
>> set(hFig, 'menuBar','none', 'toolbar','none')
>> length(getByteStreamFromArray(hFig))
ans =
       11848   %!!!
% Plot lines are not nearly as "expensive" as the toolbar/menubar
>> x=0:.01:5; hp=plot(x,sin(x));
>> byteStream = getByteStreamFromArray(hFig);
>> length(byteStream)
ans =
       33088
>> delete(hFig);
>> hFig2 = getArrayFromByteStream(byteStream)
hFig2 =
	figure
</pre>
<p>The interesting thing here is that when we deserialize a byte-stream of an HG object, it is automatically rendered onscreen. This could be very useful for persistence mechanisms of GUI applications. For example, we can save the figure handles in file so that if the application crashes and relaunches, it simply loads the file and we get exactly the same GUI state, complete with graphs and what-not, just as before the crash. Although the figure was <i><b>deleted</b></i> in the last example, deserializing the data caused the figure to reappear.<br />
We do not need to serialize the entire figure. Instead, we could choose to serialize only a specific plot line or axes. For example:</p>
<pre lang='matlab'>
>> x=0:0.01:5; hp=plot(x,sin(x));
>> byteStream = getByteStreamFromArray(handle(hp));  % 1x13080 uint8 array
>> hLine = getArrayFromByteStream(byteStream)
ans =
	graph2d.lineseries
</pre>
<p>This could also be used to easily clone (copy) any figure or other HG object, by simply calling <i><b>getArrayFromByteStream</b></i> (note the corresponding <i><b>copyobj</b></i> function, which I bet uses the same underlying mechanism).<br />
Also note that unlike HG objects, deserialized timers are NOT automatically restarted; perhaps the <b>Running</b> property is labeled <code>transient</code> or <code>dependent</code>. Properties defined with these attributes are <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/matlab_oop/understanding-the-save-and-load-process.html">apparently not serialized</a>.</p>
<h3 id="Performance">Performance aspects</h3>
<p>Using the builtin <i><b>getByteStreamFromArray</b></i> and <i><b>getArrayFromByteStream</b></i> functions can provide significant performance speedups when caching Matlab data. In fact, it could be used to store otherwise unsupported objects using the <i><b>save -v6</b></i> or <i><b>savefast</b></i> alternatives, which I discussed in my <a target="_blank" href="/articles/improving-save-performance/"><i><b>save</b></i> performance article</a>. Robin Ince has <a target="_blank" rel="nofollow" href="http://www.robinince.net/blog/2013/06/18/saving-structures-quickly-with-serialization/">shown</a> how this can be used to reduce the combined caching/uncaching run-time from 115 secs with plain-vanilla <i><b>save</b></i>, to just 11 secs using <i><b>savefast</b></i>. Robin hasn&#8217;t tested this in his post, but since the serialized data is a simple <code>uint8</code> array, it is intrinsically supported by the <i><b>save -v6</b></i> option, which is the fastest alternative of all:</p>
<pre lang='matlab'>
>> byteStream = getByteStreamFromArray(hFig);
>> tic, save('test.mat','-v6','byteStream'); toc
Elapsed time is 0.001924 seconds.
>> load('test.mat')
>> data = load('test.mat')
data =
    byteStream: [1x33256 uint8]
>> getArrayFromByteStream(data.byteStream)
ans =
	figure
</pre>
<p>Moreover, we can now use <code>java.util.Hashtable</code> to store a cache map of any Matlab data, rather than use the much slower and more limited <i><b>containers.Map</b></i> class provided in Matlab.<br />
Finally, note that as built-in functions, these functions could change without prior notice on any future Matlab release.</p>
<h3 id="MEX">MEX interface &#8211; mxSerialize/mxDeserialize</h3>
<p>To complete the picture, MEX includes a couple of undocumented functions <i>mxSerialize</i> and <i>mxDeserialize</i>, which correspond to the above functions. <i><b>getByteStreamFromArray</b></i> and <i><b>getArrayFromByteStream</b></i> apparently call them internally, since they provide the same results. Back in 2007, Brad Phelan wrote a MEX wrapper that could be used directly in Matlab (<a target="_blank" rel="nofollow" href="https://sccn.ucsd.edu/svn/software/tags/EGLAB7_0_1_3beta/external/fileio-20090511/private/mxSerialize.c">mxSerialize.c</a>, <a target="_blank" rel="nofollow" href="https://sccn.ucsd.edu/svn/software/tags/EGLAB7_0_1_3beta/external/fileio-20090511/private/mxDeserialize.c">mxDeserialize.c</a>). The C interface was very simple, and so was the usage:</p>
<pre lang='cpp'>
#include "mex.h"
EXTERN_C mxArray* mxSerialize(mxArray const *);
EXTERN_C mxArray* mxDeserialize(const void *, size_t);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nlhs && nrhs) {
          plhs[0] = (mxArray *) mxSerialize(prhs[0]);
        //plhs[0] = (mxArray *) mxDeserialize(mxGetData(prhs[0]), mxGetNumberOfElements(prhs[0]));
    }
}
</pre>
<p>Unfortunately, MathWorks has removed the C interface for these functions from <i>libmx</i> in R2014a, keeping only their C++ interfaces:</p>
<pre lang='cpp'>
mxArray* matrix::detail::noninlined::mx_array_api::mxSerialize(mxArray const *anyData)
mxArray* matrix::detail::noninlined::mx_array_api::mxDeserialize(void const *byteStream, unsigned __int64 numberOfBytes)
mxArray* matrix::detail::noninlined::mx_array_api::mxDeserializeWithTag(void const *byteStream, unsigned __int64 numberOfBytes, char const* *tagName)
</pre>
<p>These are not the only MEX functions that were removed from <i>libmx</i> in R2014a. Hundreds of other C functions were also removed with them, some of them quite important (e.g., <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/19813718/mex-files-how-to-return-an-already-allocated-matlab-array"><i>mxCreateSharedDataCopy</i></a>). A few hundred new C++ functions were added in their place, but I fear that these are not accessible to MEX users without a code change (see below). <i>libmx</i> has always changed between Matlab releases, but not so drastically for many years. If you rely on any undocumented MEX functions in your code, now would be a good time to recheck it, before R2014a is officially released.<br />
Thanks to Bastian Ebeling, we can still use these interfaces in our MEX code by simply renaming the MEX file from .c to .cpp and modifying the code as follows:</p>
<pre lang='cpp'>
#include "mex.h"
// MX_API_VER has unfortunately not changed between R2013b and R2014a,
// so we use the new MATRIX_DLL_EXPORT_SYM as an ugly hack instead
#if defined(__cplusplus) && defined(MATRIX_DLL_EXPORT_SYM)
    #define EXTERN_C extern
    namespace matrix{ namespace detail{ namespace noninlined{ namespace mx_array_api{
#endif
EXTERN_C mxArray* mxSerialize(mxArray const *);
EXTERN_C mxArray* mxDeserialize(const void *, size_t);
// and so on, for any other MEX C functions that migrated to C++ in R2014a
#if defined(__cplusplus) && defined(MATRIX_DLL_EXPORT_SYM)
    }}}}
    using namespace matrix::detail::noninlined::mx_array_api;
#endif
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nlhs && nrhs) {
        plhs[0] = (mxArray *) mxSerialize(prhs[0]);
      //plhs[0] = (mxArray *) mxDeserialize(mxGetData(prhs[0]), mxGetNumberOfElements(prhs[0]));
    }
}
</pre>
<p>Unfortunately, pre-R2014a code cannot coexist with R2014a code (since <i>libmx</i> is different), so separate MEX files need to be used depending on the Matlab version being used. This highlights the risk of using such unsupported functions.<br />
The roundabout alternative is of course to use <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/apiref/mexcallmatlab.html"><i>mexCallMATLAB</i></a> to invoke <i><b>getByteStreamFromArray</b></i> and <i><b>getArrayFromByteStream</b></i>. This is actually rather silly, but it works&#8230;<br />
p.s. &#8211; Happy 30th anniversary, MathWorks!</p>
<h3 id="addendum">Addendum March 9, 2014</h3>
<p>Now that the official R2014a has been released, I am happy to report that most of the important MEX functions that were removed in the pre-release have been restored in the official release. These include <i><a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/19813718/mex-files-how-to-return-an-already-allocated-matlab-array">mxCreateSharedDataCopy</a>, <a target="_blank" rel="nofollow" href="http://www.mathworks.com.au/matlabcentral/answers/58055-faster-way-to-initilize-arrays-via-empty-matrix-multiplication#answer_70351">mxFastZeros</a>, <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/31362-uninit-create-an-uninitialized-variable-like-zeros-but-faster">mxCreateUninitDoubleMatrix</a>, mxCreateUninitNumericArray, mxCreateUninitNumericMatrix and <a target="_blank" href="/articles/accessing-private-object-properties/">mxGetPropertyShared</a></i>. Unfortunately, <i>mxSerialize</i> and <i>mxDeserialize</i> remain among the functions that were left out, which is a real pity considering their usefulness, but we can use one of the workarounds mentioned above. At least those functions that were critical for in-place data manipulation and improved MATLAB performance have been restored, perhaps in some part due to lobbying by yours truly and by others.<br />
MathWorks should be commended for their meaningful dialog with users and for making the fixes in such a short turn-around before the official release, despite the fact that they belong to the undocumented netherworld. MathWorks may appear superficially to be like any other corporate monolith, but when you scratch the surface you discover that there are people there who really care about users, not just the corporate bottom line. I must say that I really like this aspect of their corporate culture.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data">Serializing/deserializing Matlab data</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/inter-matlab-data-transfer-with-memcached" rel="bookmark" title="Inter-Matlab data transfer with memcached">Inter-Matlab data transfer with memcached </a> <small>The memcached library can be used to transfer data between separate Matlab processes (sessions). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/controlling-plot-data-tips" rel="bookmark" title="Controlling plot data-tips">Controlling plot data-tips </a> <small>Data-tips are an extremely useful plotting tool that can easily be controlled programmatically....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-mex-in-place-editing" rel="bookmark" title="Matlab mex in-place editing">Matlab mex in-place editing </a> <small>Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/draggable-plot-data-tips" rel="bookmark" title="Draggable plot data-tips">Draggable plot data-tips </a> <small>Matlab's standard plot data-tips can be customized to enable dragging, without being limitted to be adjacent to their data-point. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/serializing-deserializing-matlab-data/feed</wfw:commentRss>
			<slash:comments>23</slash:comments>
		
		
			</item>
		<item>
		<title>Accessing private object properties</title>
		<link>https://undocumentedmatlab.com/articles/accessing-private-object-properties?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=accessing-private-object-properties</link>
					<comments>https://undocumentedmatlab.com/articles/accessing-private-object-properties#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 18 Dec 2013 18:00:00 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[MCOS]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4512</guid>

					<description><![CDATA[<p>Private properties of Matlab class objects can be accessed (read and write) using some undocumented techniques. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/accessing-private-object-properties">Accessing private object properties</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties" rel="bookmark" title="getundoc &#8211; get undocumented object properties">getundoc &#8211; get undocumented object properties </a> <small>getundoc is a very simple utility that displays the hidden (undocumented) properties of a specified handle object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-object-as-default-class-property-value" rel="bookmark" title="Handle object as default class property value">Handle object as default class property value </a> <small>MCOS property initialization has a documented but unexpected behavior that could cause many bugs in user code. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Some time ago, I needed to modify a property value of a class object. The problem was that this property was declared as <code><b>private</b></code> and for some reason my client could not modify the originating classdef to make this property accessible.</p>
<h3 id="Problem">Problem definition</h3>
<p>We start with a very simple class definition:<br />
<figure style="width: 200px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Inaccessible private property (or is it?)" src="https://undocumentedmatlab.com/images/do_not_enter_sign_200x212.jpg" title="Inaccessible private property (or is it?)" width="200" height="212" /><figcaption class="wp-caption-text">Inaccessible private property (or is it?)</figcaption></figure>   </p>
<pre lang='matlab'>
classdef MyClass
    properties (SetAccess=private)  %GetAccess = public
        y
    end
    properties (Access=private)  %GetAccess = SetAccess = private
        x
    end
    methods
        function obj = MyClass(x,y)  % constructor
            if nargin>0, obj.x = x; end
            if nargin>1, obj.y = y; end
        end
        function result = isPropEqualTo(obj,propName,value)
            result = (obj.(propName)==value);
        end
    end
end
</pre>
<p>The problem is simple: we need to both get and set the value of inaccessible private properties x,y. But following object construction, <code>MyClass</code> enables direct read access only to property y, and write access to neither of its properties:</p>
<pre lang='matlab'>
>> obj = MyClass(3,4)
obj =
  MyClass with properties:
    y: 4
>> obj.x
You cannot get the 'x' property of MyClass.
>> obj.x=5
You cannot set the 'x' property of MyClass.
>> obj.y=5
You cannot set the read-only property 'y' of MyClass.
</pre>
<p>A dead end, would you say? &#8211; Well, it never stopped us before, has it? After all, is it not the raison-d&#8217;être of this blog?<br />
<span id="more-4512"></span></p>
<h3 id="Get">Reading private properties</h3>
<p>Getting the value of x is simple enough when we recall that <a target="_blank" href="/articles/matlab-java-memory-leaks-performance/#struct">calling Matlab&#8217;s <i><b>struct</b></i> function on a class object</a> reveals all its hidden treasures. I wrote about this a couple of years ago, and I&#8217;m not sure how many people realize the power of this undocumented feature:</p>
<pre lang='c'>
>> s = struct(obj)
Warning: Calling STRUCT on an object prevents the object from hiding its implementation details and should thus be avoided.
Use DISP or DISPLAY to see the visible public details of an object. See 'help struct' for more information.
(Type "warning off MATLAB:structOnObject" to suppress this warning.)
s =
    y: 4
    x: 3
</pre>
<p>As the warning mentions, we should not do this often (bad, bad boy!). If we must (I promise I had a good reason, ma!), then we can simply turn off the nagging warning:</p>
<pre lang='matlab'>warning off MATLAB:structOnObject</pre>
<p>We can now read all the private internal properties of the object. Yummy!</p>
<h3 id="Set">Setting private properties</h3>
<p>The natural attempt would now be to update the struct&#8217;s fields with new values. Unfortunately, this does not affect the original class properties, since our struct is merely a copy of the original. Even if our original object is a handle class, the struct would still be a <a target="_blank" href="/articles/class-object-creation-performance/#comment-303863">shallow copy</a> and not a real reference to the object data.<br />
Mex&#8217;s standard <i>mxGetProperty</i> cannot be used on the original object, because <i>mxGetProperty</i> returns a copy of the property (not the original reference &#8211; probably to prevent exactly what I&#8217;m describing here&#8230;), and in any case it can&#8217;t access private properties. <i>mxSetProperty</i> is a dead-end for similar reasons.<br />
The core idea behind the solution is <a target="_blank" href="/articles/internal-matlab-memory-optimizations/">Matlab&#8217;s Copy-on-Write mechanism</a> (COW). This basically means that when our struct is created, the field values actually hold references (pointers) to the original object properties. It is only when trying to <i>modify</i> the struct fields that COW kicks in and a real copy is made. This is done automatically and we do not have any control over it. However, we can use this information to our advantage by retrieving the field references (pointers) <i>before</i> COW has a chance to ruin them. Once we have the reference to the private data, we can <a target="_blank" href="/articles/matlab-mex-in-place-editing/">modify the data in-place using a bit of Mex</a>.<br />
So the trick is to get the reference address (pointer) of <code>s.x</code> and <code>s.y</code>. How do we do that?<br />
We can use another trick here, which is a corollary to the COW mechanism: when we pass <code>s.x</code> into a function, it is not a data copy that is being passed (<i>by value</i>), but rather its pointer (<i>by reference</i>). So we can simply get this pointer in our Mex function and use it to modify the original property value. Easy enough, right?<br />
Not so fast. Don&#8217;t forget that <code>s.x</code> is merely a reference copy of the original property data. If we modify <code>s.x</code>&#8216;s reference we&#8217;re just killing the so-called <i><a target="_blank" rel="nofollow" href="http://www.mk.tu-berlin.de/Members/Benjamin/mex_sharedArrays">cross-link of the shared-array</a></i>. What we need to do (more or less) is to traverse this cross-link back to its source, to get the <i>real</i> reference to the data.<br />
Sounds complicated? Well, it is a bit. Luckily, Mex guru James (Jim) Tursa comes to the rescue with his <i><a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/30672-mxgetpropertyptr-c-mex-function">mxGetPropertyPtr</a></i> function on the File Exchange, which does all that for us. Once we have it compiled (the utility automatically Mex-compiles itself on first use), we can use it as follows (note the highlighted line using <i>mxGetPropertyPtr</i>):</p>
<pre lang='c' highlight='20'>
/* Place in mxMySetProperty.c and mex-compile*/
#include "mex.h"
#include "mxGetPropertyPtr.c"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    mxArray *x;
    register double *xpr;
    int buflen;
    char *propName = "x";
    double newValue = -3.14159265358979;
    if ( nrhs > 1 ) {
        /* Get the specified property name (or "x" if not specified) */
        buflen = mxGetNumberOfElements(prhs[1]) + 1;
        propName = mxCalloc(buflen, sizeof(char));
        mxGetString(prhs[1], propName, buflen);
    }
    /* Get the pointer to the original property data */
    x = mxGetPropertyPtr(prhs[0],0,propName);
    if ( !x ) {
        mexErrMsgTxt("Failed to get pointer to property.");
    }
    /* Display the existing property value */
    xpr = mxGetPr(x);
    mexPrintf("existing value of property %s = %f\n", propName, *xpr);
    /* Update the property with the new value */
    if ( nrhs > 2 ) {
        /* Get the specified new value (or -pi if not specified) */
        double *pr = mxGetPr(prhs[2]);
        newValue = *pr;
    }
    mexPrintf("setting value of property %s to %f\n", propName, newValue);
    *xpr = newValue;
}
</pre>
<p>Naturally, this simplistic Mex function should also be made to accept non-scalar values. This is left as an exercise to the reader.<br />
The usage in Matlab of this <i>mxMySetProperty</i> function is super simple:</p>
<pre lang='matlab'>
% Update obj.x from 3 => pi/2
>> mxMySetProperty(s,'x',pi/2);
existing value of property x = 3.000000
setting value of property x to 1.570796
% Update obj.y from 4 => -5
>> mxMySetProperty(s,'y',-5);  % here we can also use obj instead of s since obj.y is accessible
existing value of property y = 4.000000
setting value of property y to -5.000000
% Check that the struct copy has been updated correctly
>> s
s =
    y: -5
    x: 1.5707963267949
% Check that the original object's private properties have been updated correctly
>> obj
obj =
  MyClass with properties:
    y: -5
>> obj.isPropEqualTo('x',pi/2)
ans =
    1     % ==true
</pre>
<p>Jim Tursa has promised to supply a <i>mxSetPropertyPtr</i> variant of his <i>mxGetPropertyPtr</i> for the past two years (<a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/30672-mxgetpropertyptr-c-mex-function">1</a>,<a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/4682#answer_6618">2</a>,<a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/answers/25247#comment_56121">3</a>,<a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/answers/79046">4</a>). It will surely be more robust than my simplistic <i>mxMySetProperty</i> function, so I look forward to finally seeing it on FEX!</p>
<h3 id="Conclusion">Conclusion</h3>
<p>With some dirty tricks and undocumented hacks, we can both get and set private-access object properties. Please don&#8217;t do this unless you have a really good reason (such as a customer breathing down your neck, who doesn&#8217;t give a fig that his properties were declared private&#8230;).<br />
The mechanism shown above can also be used to improve performance when updating public object properties, since it updates the data in-place rather than create a copy. This could be significant when the property size is very large (multi-MB), since it avoids unnecessary memory allocation and deallocation. You might think that with public properties we could use the standard <i>mxGetProperty</i> for this, but as I said above this function apparently returns a copy of the data, not a direct reference. Also note that last month I discussed additional <a target="_blank" href="/articles/performance-accessing-handle-properties/">performance aspects of accessing object properties</a>.<br />
This blog will now take a short break for the holidays. I hope you had a good ride this year, see you again on the other side of 2013.<br />
Merry Christmas and happy New-Year everybody! </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/accessing-private-object-properties">Accessing private object properties</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/getundoc-get-undocumented-object-properties" rel="bookmark" title="getundoc &#8211; get undocumented object properties">getundoc &#8211; get undocumented object properties </a> <small>getundoc is a very simple utility that displays the hidden (undocumented) properties of a specified handle object....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-object-as-default-class-property-value" rel="bookmark" title="Handle object as default class property value">Handle object as default class property value </a> <small>MCOS property initialization has a documented but unexpected behavior that could cause many bugs in user code. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/accessing-private-object-properties/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Undocumented Matlab MEX API</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-matlab-mex-api</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 24 Jul 2013 18:00:30 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Pavel Holoborodko]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=4029</guid>

					<description><![CDATA[<p>Matlab's MEX API contains numerous undocumented functions, that can be extremely useful. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api">Undocumented Matlab MEX API</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uiundo-matlab-undocumented-undo-redo-manager" rel="bookmark" title="uiundo &#8211; Matlab&#039;s undocumented undo/redo manager">uiundo &#8211; Matlab&#039;s undocumented undo/redo manager </a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/reasons-for-undocumented-matlab-aspects" rel="bookmark" title="Reasons for undocumented Matlab aspects">Reasons for undocumented Matlab aspects </a> <small>There are many reasons for the numerous undocumented aspects in Matlab - this article explains them....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-book" rel="bookmark" title="New book: Undocumented Secrets of MATLAB-Java Programming">New book: Undocumented Secrets of MATLAB-Java Programming </a> <small>Undocumented Secrets of Matlab-Java Programming (ISBN 9781439869031) is a book dedicated to the integration of Matlab and Java. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to welcome guest blogger Pavel Holoborodko of <a target="_blank" rel="nofollow" href="http://www.advanpix.com/">Advanpix</a>, maker of the Multiprecision Computing Toolbox. Today, Pavel discusses undocumented MEX functions that he encountered in his work to improve the toolbox performance.</i><br />
<figure style="width: 274px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Advanpix logo" src="https://undocumentedmatlab.com/images/advanpix_logo.png" title="Advanpix logo" width="274" height="100" /><figcaption class="wp-caption-text">Advanpix logo</figcaption></figure> It is not a secret that Matlab has many undocumented (or deliberately hidden) features and commands. After all, Yair&#8217;s <a href="/" title="Undocumented Matlab" target="_blank">website</a> &#038; book are devoted specifically to this topic.<br />
However most of the findings are related to Matlab language itself and investigations on <a target="_blank" href="/articles/tag/mex/">undocumented MEX API</a> seems to be scarce.<br />
During development of our toolbox we have found lots of hidden functions which can be helpful for creating speed-efficient extensions for Matlab using native languages.<br />
Here we want to explain some of them in detail and provide complete list of undocumented MEX API functions.<br />
<span id="more-4029"></span><br />
Please note that there is a risk in using the functions &#8211; MathWorks can change / remove some of them in next versions. It is an additional burden for developers to stay tuned and update their toolboxes on time.</p>
<h3 id="OOP">Reduced OOP capabilities of Matlab</h3>
<p>Starting with R2008b Matlab allows user to introduce custom-type classes by the <i><b>classdef</b></i> keyword. Matlab was late on adding object oriented features &#8211; I can only image how hard it was for developers at MathWorks to add OOP constructs to a purely procedural language, which follows entirely different philosophy. <em>(Yes, objects could be created using structs and special folder structure in earlier version of Matlab &#8211; but that was just ugly design, MathWorks will not support it in the future)</em>.<br />
They still don&#8217;t have full support for OOP features though. The most important missing features are:</p>
<ul>
<li>It is prohibited to have a destructor for custom non-handle classes</li>
<li> It is not possible to overload assignment-without-subscripts operator (e.g. A = B)</li>
</ul>
<p>I don&#8217;t know the reasons why these fundamental OOP paradigms are not implemented in Matlab &#8211; but they surely prevent creating powerful virtual machine-type of toolboxes.<br />
In that case Matlab objects would have only one property field &#8211; &#8216;id&#8217;, identifier of variable stored in MEX module &#8211; virtual machine (e.g. pointer to C++/C object). MEX module would only need to know &#8216;id&#8217; of objects and what operation to conduct with them (+, -, *, etc.) &#8211; all processing would be done in MEX. Heavy data exchange between Matlab and MEX libraries would be completely unnecessary. Matlab would act as just an interpreter in such scenario. Moreover MEX API could be simplified to several functions only.</p>
<h3 id="Property-access">Access to object properties from MEX</h3>
<p>Unfortunately we are restricted to current architecture &#8211; where all the data are allocated / stored on Matlab side and we have to transfer it from Matlab to MEX library in order to work with it. The official MEX API provides two functions to access object properties from within MEX library: <code>mxGetProperty</code> and <code>mxSetProperty</code>.<br />
Both functions share the same problem &#8211; they create a <b>deep copy</b> of the data!<br />
Imagine the situation when your object is a huge matrix with high-precision elements and it occupies 800MB of RAM. If we want to access it in MEX library (e.g. transpose) we would call <code>mxGetProperty</code> which will do ENTIRE COPY of your object&#8217;s property &#8211; wasting another 800MB!<br />
Obviously this cannot be accepted, not speaking of totally reduced performance (copying could take a while for such amount too).<br />
In search for remedy we found a similar (but) undocumented functions we can use to get shared access to objects properties (32-bit):</p>
<pre lang="c">
extern mxArray* mxGetPropertyShared(const mxArray* pa,
                                    unsigned int index,
                                    const char * propname);
extern void mxSetPropertyShared(mxArray* pa,
                                unsigned int index,
                                const char * propname,
                                const mxArray* value);
</pre>
<p>These functions can be used as one-to-one replacement of the official functions: <code>mxGetPropertyShared</code> just returns pointer to existing property without any copying; <code>mxDestroyArray</code> can still be called on returned pointer (<i>thanks to James Tursa for the correction</i>).</p>
<h3 id="full-list">Full list of MEX API functions</h3>
<p>We have extracted the full list of usable MEX functions from <i>libmx.dll</i> and <i>libmex.dll</i> (Matlab R2012b Windows 32-bit) &#8211; the two main MEX API dynamic libraries. It includes functions from the official API as well as undocumented ones (which are in fact the majority):</p>
<ul>
<li><a href="http://www.advanpix.com/wp-content/plugins/download-monitor/download.php?id=11" title="LIBMX.DLL All Functions" target="_blank">libmx</a> (856 exported functions)</li>
<li><a href="http://www.advanpix.com/wp-content/plugins/download-monitor/download.php?id=10" title="LIBMEX.DLL All Functions" target="_blank">libmex</a> (44 exported functions)</li>
</ul>
<p>The distinctive feature of the list &#8211; it provides de-mangled C++ names of functions, with type of arguments and return value. This makes usage of undocumented functions much easier. You can also easily see this list using tools such as <a target="_blank" rel="nofollow" href="http://www.nirsoft.net/utils/dll_export_viewer.html">DLL Export Viewer</a> or the well-known <a target="_blank" rel="nofollow" href="http://www.dependencywalker.com/">Dependency Walker</a>. This list was not previously published to the knowledge of this author; a much shorter unannotated list was <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/301249#813965">posted by Yair</a> in 2011.<br />
Take a look at the function list &#8211; there are a lot of interesting ones, like <code>mxEye</code>, <code>mxIsInf</code>, <code>mxFastZeros</code>, <code>mxGetReferenceCount</code> and many others.<br />
Moreover it is possible to see high level C++ classes MathWorks developers use for work. Peter Li has <a target="_blank" href="/articles/matlabs-internal-memory-representation/">posted an article</a> about <code>mxArray_tag</code>&#8216;s evolution and internal structure in 2012. Now it is clear that the fundamental data type <code>mxArray_tag</code> is not a plain-old-struct anymore, it has member-functions and behaves more like a class. It even has custom <code>new</code>/<code>delete</code> heap management functions and overloaded assignment <code>operator=</code>. Reverse-engineering of these functions might reveal the exact &#038; complete data structure of <code>mxArray_tag</code>, but perhaps this is not allowed by the Matlab license agreement.<br />
Anyway, with some effort, the internal <code>mxArray_tag</code> class from MathWorks might be used in third-party MEX files. How much more easier this would be instead of clumsy <code>mx****</code> functions!<br />
Please feel free to leave your requests or comments below.<br />
<i>Note: This article was originally <a target="_blank" rel="nofollow" href="http://www.advanpix.com/2013/07/19/undocumented-mex-api/">posted</a> on the Advanpix blog; reposted here with kind permission and a few changes.</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api">Undocumented Matlab MEX API</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uiundo-matlab-undocumented-undo-redo-manager" rel="bookmark" title="uiundo &#8211; Matlab&#039;s undocumented undo/redo manager">uiundo &#8211; Matlab&#039;s undocumented undo/redo manager </a> <small>The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/reasons-for-undocumented-matlab-aspects" rel="bookmark" title="Reasons for undocumented Matlab aspects">Reasons for undocumented Matlab aspects </a> <small>There are many reasons for the numerous undocumented aspects in Matlab - this article explains them....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-book" rel="bookmark" title="New book: Undocumented Secrets of MATLAB-Java Programming">New book: Undocumented Secrets of MATLAB-Java Programming </a> <small>Undocumented Secrets of Matlab-Java Programming (ISBN 9781439869031) is a book dedicated to the integration of Matlab and Java. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-matlab-mex-api/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Parsing mlint (Code Analyzer) output</title>
		<link>https://undocumentedmatlab.com/articles/parsing-mlint-code-analyzer-output?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=parsing-mlint-code-analyzer-output</link>
					<comments>https://undocumentedmatlab.com/articles/parsing-mlint-code-analyzer-output#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 10 Apr 2013 18:00:28 +0000</pubDate>
				<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=3713</guid>

					<description><![CDATA[<p>The Matlab Code Analyzer (mlint) has a lot of undocumented functionality just waiting to be used. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/parsing-mlint-code-analyzer-output">Parsing mlint (Code Analyzer) output</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/runtime-code-instrumentation" rel="bookmark" title="Runtime code instrumentation">Runtime code instrumentation </a> <small>Conditional breakpoints can be used to instrument code with user-specified code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/parsing-xml-strings" rel="bookmark" title="Parsing XML strings">Parsing XML strings </a> <small>Matlab's xmlread function cannot process XML data directly, but this can easily be overcome. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/running-vb-code-in-matlab" rel="bookmark" title="Running VB code in Matlab">Running VB code in Matlab </a> <small>Matlab does not natively enable running VB code, but a nice trick enables us to do just that...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/function-definition-meta-info" rel="bookmark" title="Function definition meta-info">Function definition meta-info </a> <small>There are multiple ways to retrieve meta-info about functions in Matlab. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Mlint, Matlab&#8217;s static code-analysis parser, was written by <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Stephen_C._Johnson">Stephen Johnson</a> (the original developer of the enormously successful <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Lint_(software)">lint</a> parser for C/C++ back in 1977), when he was lured by MathWorks in 2002 to develop a similar tool for Matlab. Since its development (in R14 I believe), and especially since its incorporation in Matlab&#8217;s Editor in R2006a (Matlab 7.2), mlint has become a very important tool for reporting potential problems in m-files.<br />
Unfortunately, to this day (R2013a), there is no <i>documented</i> manner of programmatically separating mlint warnings and errors, nor for accessing any of the multitude of features that are readily available in mlint. Naturally, there is (and has always been) an undocumented back door.<br />
From its earliest beginnings, mlint has relied on C code (presumably modeled after lint). For many years mlint relied on a mex file (<i>%matlabroot%/toolbox/matlab/codetools/mlintmex.mex*</i>), which is basically just a wrapper for <i>mlint.dll</i> where the core algorithm resides. In recent releases, <i><b>mlintmex</b></i>, just like many other core mex files, was ported into a core Matlab library (<i>libmwbuiltins.dll</i> on Windows). However, the name and interface of the <i><b>mlintmex</b></i> function have remained unchanged over the years. Wrapping the core <i><b>mlintmex</b></i> function is the <i><b>mlint</b></i> m-function (<i>%matlabroot%/toolbox/matlab/codetools/mlint.m</i>) that calls <i><b>mlintmex</b></i> internally. In R2011b (Matlab 7.13) its official function name has changed to <i><b>checkcode</b></i>, although this was never documented in the release notes for some reason. However, using <i><b>mlint</b></i> still works even today. Wrapping all that is the <i><b>mlintrpt</b></i> function, which calls <i><b>mlint/checkcode</b></i> internally.<br />
The core function <i><b>mlintmex</b></i> returns a long string with embedded newlines to separate the messages. For example:</p>
<pre lang='java'>
>> str = mlintmex('perfTest.m')
str =
L 3 (C 1): The value assigned to variable 'A' might be unused.
L 4 (C 1): The value assigned to variable 'B' might be unused.
L 5 (C 1-3): Variable 'ops', apparently a structure, is changed but the value seems to be unused.
L 12 (C 9): This statement (and possibly following ones) cannot be reached.
L 53 (C 19-25): The function 'subFunc' might be unused.
L 53 (C 27-35): Input argument 'iteration' might be unused. If this is OK, consider replacing it by ~.
</pre>
<p><span id="more-3713"></span><br />
We can parse this long string ourselves, but there is no need since <i><b>mlint/checkcode</b></i> do this for us, returning a struct array:</p>
<pre lang='java'>
>> results = mlint('perfTest.m')
results =
6x1 struct array with fields:
    message
    line
    column
    fix
>> results(5)
ans =
    message: 'The function 'subFunc' might be unused.'
       line: 53
     column: [19 25]
        fix: 0
</pre>
<p>As can be seen, the message severity (warning/error) does not appear. This severity is obviously available since it is integrated in the Editor and the Code Analyzer report &#8211; orange for warnings, red for errors.<br />
In one of my projects I needed to enable the user to dynamically create executable Matlab code that would then be run interactively. This enabled users to create dynamic data analyses functions without actually needing to know Matlab or to code all the nuts-and-bolts of a regular Matlab function. For this I needed to display warnings and errors-on-the-fly (the dynamic cell tooltips used a <a target="_blank" href="/articles/uitable-cell-colors/#colors">custom table cell-renderer</a>). Here&#8217;s the end-result:<br />
<center><br />
<figure style="width: 656px" class="wp-caption aligncenter"><img decoding="async" alt="Analysis definition panel" src="https://undocumentedmatlab.com/images/IDS_DefsAnalyses2.png" title="Analysis definition panel" width="656" /><figcaption class="wp-caption-text">Analysis definition panel</figcaption></figure><br />
<figure style="width: 637px" class="wp-caption aligncenter"><img decoding="async" alt="Dynamic analysis alert tooltips" src="https://undocumentedmatlab.com/images/IDS_DefsAnalyses3b.png" title="Dynamic analysis alert tooltips" width="508" /><br /><img decoding="async" alt="Dynamic analysis alert tooltips" src="https://undocumentedmatlab.com/images/IDS_DefsAnalyses3c.png" title="Dynamic analysis alert tooltips" width="637" /><figcaption class="wp-caption-text">Dynamic analysis alert tooltips</figcaption></figure><br />
</center><br />
My <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/255839#755939">solution</a> was to use <i><b>mlintmex</b></i>, as follows:</p>
<pre lang='matlab'>
% Get the relevant message strings
errMsgs = mlintmex('-m2', srcFileName);
allMsgs = mlintmex('-m0', srcFileName);
% Parse the strings to find newline characters
numErrors = length(strfind(regexprep(errMsgs,'\*\*\*.*',''),char(10)));
numAllMsg = length(strfind(regexprep(allMsgs,'\*\*\*.*',''),char(10)));
numWarns = numAllMsg - numErrors;
</pre>
<p>(and from the messages themselves [<code>errMsgs,allMsgs</code>] I extracted the actual error/warning location)<br />
Alternatively, I could have used <i><b>mlint</b></i> directly, as I have recently <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/54903-does-checkcode-return-the-status-of-the-message-indicator-box-i-e-red-orange-green">explained</a>:</p>
<pre lang='matlab'>
% Note that mlint returns struct arrays, so the following are all structs, not strings
errMsgs = mlint('-m2',srcFileNames); % m2 = errors only
m1Msgs  = mlint('-m1',srcFileNames); % m1 = errors and severe warnings only
allMsgs = mlint('-m0',srcFileNames); % m0 = all errors and warnings
</pre>
<p>The original information about <i><b>mlintmex</b></i> and the undocumented -m0/m1/m2 options came from <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/authors/4309">Urs (us) Schwartz</a>, whose contributions are an endless source of such gems. Urs also <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/255839#756892">provided</a> a list of other undocumented <i><b>mlint</b></i> options (the comment annotations are mostly mine):</p>
<pre lang='matlab'>
'-all'        % ???
'-allmsg'     % display the full list of possible mlint messages and their codes
'-amb'        % display all possibly-ambiguous identifiers (variable/function)
'-body'       % ???
'-callops'    % display the internal call tree, with nesting levels and function types
'-calls'      % (looks similar to -callops, not sure what the difference is)
'-com'        % ???
'-cyc'        % display McCabe complexity value of all functions in the analyzed file
% '-db'       % == -set + -ud + -tab
'-dty'        % debug info for the mlint parsing tree
'-edit'       % display all encountered identifiers and their assumed types
'-en'         % messages in English
'-id'         % display the mlint code associated with each message
'-ja'         % messages in Japanese
'-lex'        % display the LEX parse-tree for the analyzed file
'-m0'         % + other opt
'-m1'         % + other opt
'-m2'         % + other opt
'-m3'         % + other opt
'-mess'       % debug info for mlint message-reporting (start/end locations etc.)
'-msg'        % (looks similar to -allmsg above, not sure what the difference is)
'-notok'      % disregard %#ok directives and report messages on lines having them
'-pf'         % ???
'-set'        % debug info for the mlint parsing tree
'-spmd'       % ??? (presumably display SPMD-related messages)
'-stmt'       % display the number of statements in each function within the analyzed file
'-tab'        % set-by/used-by table for all identifiers (see -edit)
'-tmtree'     % not valid anymore
'-tmw'        % not valid anymore
'-toks'       % ???
'-tree'       % debug info for the mlint parsing tree
'-ty'         % display the line numbers where each of the file's identifiers are used
'-ud'         % debug info for the mlint parsing tree
'-yacc'       % ONLY: !mlint FILE -yacc -...
</pre>
<p>to which were added in recent years &#8216;-eml&#8217;, &#8216;-codegen&#8217; etc. &#8211; see the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/checkcode.html"><i><b>checkcode</b></i> doc page</a>. Also note that not all Matlab releases support all options. For example, &#8216;-tmw&#8217; is ignored in R2013a, returning the same data as &#8216;-all&#8217; plus a warning about the ignored option.<br />
Urs prepared a short utility called <a target="_blank" href="/files/doli.m">doli</a> that accepts an m-file name and returns a struct whose fields are the respective outputs of <i><b>mlint</b></i> for each of the corresponding options:</p>
<pre lang='java'>
>> results = doli('perfTest.m')
MLINT >   C:\Yair\Books\MATLAB Performance Tuning\Code\perfTest.m
OPTION>   -all       6
OPTION>   -allmsg    501
OPTION>   -amb       17
OPTION>   -body      6
OPTION>   -callops   15
OPTION>   -calls     15
OPTION>   -com       6
OPTION>   -cyc       8
OPTION>   -dty       162
OPTION>   -edit      92
OPTION>   -en        7
...
</pre>
<p>Some of these options are used by Urs&#8217; <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/15924-farg-a-pedestrian-m-file-parser-showing-all-used-functions-syntax"><i><b>farg</b></i></a> and <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17291-fdep-a-pedestrian-function-dependencies-finder"><i><b>fdep</b></i></a> utilities. Their usage of <i><b>mlint</b></i> rather than direct m-code parsing, is part of the reason that these functions are so lightningly fast.<br />
For example, we can use the &#8216;-calls&#8217; options to parse an m-file and get the names, type, and code location of its contained functions (<a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/145245#365590">explanation</a>):</p>
<pre lang='java'>
>> mlint('-calls','perfTest.m')
M0 1 10 perfTest
E0 51 3 perfTest
U1 3 5 randi
U1 4 5 num2cell
U1 4 14 randn
U1 6 1 whos
U1 7 1 tic
U1 7 6 save
U1 7 45 toc
U1 9 6 savefast
S0 53 19 subFunc
E0 60 3 subFunc
U1 55 8 isempty
U1 56 20 load
U1 57 29 sin
</pre>
<p>With so many useful features, I really cannot understand why they were never exposed to the public in a documented manner. After all, they have remained pretty-much unchanged for many years and can provide enormous benefits for developers of unit-tests and interactive analysis frameworks (as I have shown above).<br />
As a side-note, in R2010a (Matlab 7.10), mlint was renamed &#8220;Code Analyzer&#8221;, but this was really just a name change &#8211; its core functionality has changed little in the past decade. Some might argue that new checks were added and the Editor interface has improved by allowing auto-fixes and message suppression. But for a tool that is over a decade old (much more, if you count lint&#8217;s development), I contend that these are not much. Don&#8217;t get me wrong &#8211; I have the utmost respect for Steve. Serious unix C/C++ development relies on his lint and yacc tools on a regular basis. I think they show astonishing ingenuity and intelligence. It&#8217;s just that I had expected more after a decade of mlint development (I bet it&#8217;s not due to Steve suddenly losing the touch).<br />
<b><u>Addendum:</u></b> A little birdie tells me that Steve left MathWorks a few years ago, which does explain things&#8230; I apologize to Steve for any misguided snide on my part. As I said above, I have nothing but the utmost respect for his work. The question of why MathWorks left his mlint work hanging without serious continuation remains open.<br />
<b><u>Addendum 2:</u></b> Additional and much more detailed information about the nature of functions can be found using the semi-documented <a target="_blank" href="/articles/function-definition-meta-info/"><i><b>mtree</b></i> function</a> (or rather, Matlab class: <i>%matlabroot%/toolbox/matlab/codetools/@mtree/mtree.m</i>). This is a huge class-file (3200+ lines of code) that is well worth a dedicated future article, so stay tuned&#8230;</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/parsing-mlint-code-analyzer-output">Parsing mlint (Code Analyzer) output</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/runtime-code-instrumentation" rel="bookmark" title="Runtime code instrumentation">Runtime code instrumentation </a> <small>Conditional breakpoints can be used to instrument code with user-specified code. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/parsing-xml-strings" rel="bookmark" title="Parsing XML strings">Parsing XML strings </a> <small>Matlab's xmlread function cannot process XML data directly, but this can easily be overcome. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/running-vb-code-in-matlab" rel="bookmark" title="Running VB code in Matlab">Running VB code in Matlab </a> <small>Matlab does not natively enable running VB code, but a nice trick enables us to do just that...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/function-definition-meta-info" rel="bookmark" title="Function definition meta-info">Function definition meta-info </a> <small>There are multiple ways to retrieve meta-info about functions in Matlab. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/parsing-mlint-code-analyzer-output/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
	</channel>
</rss>
