<?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>Pavel Holoborodko &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/pavel-holoborodko/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 21 Dec 2016 15:24:06 +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>Checking status of warning messages in MEX</title>
		<link>https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=checking-status-of-warning-messages-in-mex</link>
					<comments>https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 21 Dec 2016 15:24:06 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Pavel Holoborodko]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6797</guid>

					<description><![CDATA[<p>Undocumented Mex functions can be used to extract the state of Matlab warnings in run-time. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex">Checking status of warning messages in 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/better-mex-error-messages" rel="bookmark" title="Better MEX error messages">Better MEX error messages </a> <small>The default clunky and release-incompatible MEX error messages can be improved using a simple hack. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-status-bar-text" rel="bookmark" title="Setting status-bar text">Setting status-bar text </a> <small>The Matlab desktop and figure windows have a usable statusbar which can only be set using undocumented methods. This post shows how to set the status-bar text....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-status-bar-components" rel="bookmark" title="Setting status-bar components">Setting status-bar components </a> <small>Matlab status-bars are Java containers in which we can add GUI controls such as progress-bars, not just simple text labels...</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>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I would like to welcome guest blogger Pavel Holoborodko, the developer of the <a href="http://advanpix.com" rel="nofollow" target="_blank">Advanpix Multiprecision Computing Toolbox</a>. Pavel has <a href="/articles/tag/pavel-holoborodko" target="_blank">already posted here</a> as a guest blogger about undocumented Matlab MEX functions. Today he will discuss another little-known aspect of advanced MEX programming with Matlab, a repost of an article that was <a href="http://www.advanpix.com/2016/10/24/check-status-of-warning-messages-from-mex" rel="nofollow" target="_blank">originally posted</a> on his own blog. Happy holidays everybody!</i><br />
Matlab allows flexible adjustment of visibility of warning messages. Some, or even all, messages can be disabled from showing on the screen by <i><b><a href="https://www.mathworks.com/help/matlab/matlab_prog/suppress-warnings.html" rel="nofollow" target="_blank">warning</a></b></i> command.<br />
The little known fact is that status of some warnings may be used to change the execution path in algorithms. For example, if warning <code>'Matlab:nearlySingularMatrix'</code> is disabled, then the linear system solver (<i><b>mldivide</b></i> operator) might skip estimation of reciprocal condition number which is used exactly for the purpose of detection of nearly singular matrices. If the trick is used, it allows 20%-50% boost in solver performance, since <code>rcond</code> estimation is a time consuming process.<br />
Therefore it is important to be able to retrieve status of warnings in Matlab. Especially in MEX libraries targeted for improved performance. Unfortunately Matlab provides no simple way to check status of warning message from MEX module.<br />
Today&#8217;s article outlines two workarounds for the issue:</p>
<ol>
<li>Using <code>mexCallMATLABWithTrap</code> (documented)</li>
<li>Using <code>utGetWarningStatus</code> (undocumented)</li>
</ol>
<p><span id="more-6797"></span></p>
<h3 id="mexCallMATLABWithTrap">Using mexCallMATLABWithTrap (documented)</h3>
<p>The first idea is to use documented <a href="https://www.mathworks.com/help/matlab/apiref/mexcallmatlabwithtrap.html" rel="nofollow" target="_blank"><code>mexCallMATLABWithTrap</code></a> function to execute <i><b>warning</b>(&#8216;query&#8217;,&#8230;)</i> command using Matlab&#8217;s interpreter and then parse the returned result:</p>
<pre lang="cpp">
bool mxIsWarningEnabled(const char* warningId)
{
    bool enabled = true;
    if (NULL != warningId)
    {
        mxArray *mxCommandResponse = NULL, *mxException = NULL;
        mxArray *args[2];
        /* warning('query', warningId); */
        args[0] = mxCreateString("query");
        args[1] = mxCreateString(warningId);
        mxException = mexCallMATLABWithTrap(1,&mxCommandResponse,2,args,"warning");
        if (NULL == mxException && NULL != mxCommandResponse)
        {
            if (mxIsStruct(mxCommandResponse))
            {
                const mxArray* state_field = mxGetField(mxCommandResponse, 0, "state");
                if (mxIsChar(state_field))
                {
                    char state_value[8] = {0};
                    enabled = (0 == mxGetString(state_field, state_value, 8)) &&
                              (0 == strcmp(state_value,"on"));
                }
            }
            mxDestroyArray(mxCommandResponse);
        }
        else
        {
            /* 'warning' returned with error */
            mxDestroyArray(mxException);
        }
        mxDestroyArray(args[0]);
        mxDestroyArray(args[1]);
    }
    return enabled;
}
</pre>
<p>This approach is slow, but works fine in most standard situations. See the bottom of this post for a usage example.<br />
However, this approach has an important drawback – we should be careful with recursive calls to the Matlab interpreter (<code>Matlab -> MEX -> Matlab</code>) and with <a href="http://www.advanpix.com/2016/02/14/short-and-informative-error-messages-from-mex/" rel="nofollow" target="_blank">handling Matlab errors in MEX</a>. It is safe only if we use identical standard libraries and compiler to build both MEX and Matlab.<br />
In other cases, for example when MEX is targeted to work with different versions of Matlab, or was built with a different standard library and compiler, etc. – cross boundary handling of errors (which are just C++ exceptions) might lead to unpredictable results, most likely segfaults.</p>
<h3 id="utGetWarningStatus">Using utGetWarningStatus (undocumented)</h3>
<p>To avoid all the overhead of calling Matlab interpreter and unsafe error handling, we can use some undocumented internal Matlab functions:</p>
<pre lang="cpp">
/* Link with libut library to pick-up undocumented functions: */
extern "C" void* utGetWarningManagerContext(void);
extern "C" bool  utIsValidMessageIdentifier(const char *warningId);
extern "C" bool  utGetWarningStatus(void* context, const char *warningId);
/*
   Returns true if warning with warningId enabled
   Matlab versions supported/tested: R2008b - R2016b
*/
bool mxIsWarningEnabled(const char *warningId)
{
    bool enabled = true;
    if (NULL != warningId && utIsValidMessageIdentifier(warningId))
    {
        void* context = utGetWarningManagerContext();
        enabled = (NULL != context) && utGetWarningStatus(context, warningId);
    }
    return enabled;
}
</pre>
<p>Now the code is clean, fast and safe – we bypass the interpreter and work directly with Matlab kernel. All the undocumented functions involved are present in Matlab for at least 10 years and do simple logical checks under the hood.<br />
The standard function <code><a href="https://www.mathworks.com/help/matlab/apiref/mexwarnmsgidandtxt.html" rel="nofollow" target="_blank">mexWarnMsgIdAndTxt</a></code> uses similar code to check if it should display the warning or just suppress it, and that code remains unchanged since R2008b. This is a good indication of code stability and makes us believe that it will not be changed in future versions of Matlab.<br />
For both workarounds, usage is simple:</p>
<pre lang="cpp">
if (mxIsWarningEnabled("Matlab:nearlySingularMatrix"))
{
   /* compute rcond */
}
else
{
   /* do something else */
}
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex">Checking status of warning messages in 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/better-mex-error-messages" rel="bookmark" title="Better MEX error messages">Better MEX error messages </a> <small>The default clunky and release-incompatible MEX error messages can be improved using a simple hack. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-status-bar-text" rel="bookmark" title="Setting status-bar text">Setting status-bar text </a> <small>The Matlab desktop and figure windows have a usable statusbar which can only be set using undocumented methods. This post shows how to set the status-bar text....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/setting-status-bar-components" rel="bookmark" title="Setting status-bar components">Setting status-bar components </a> <small>Matlab status-bars are Java containers in which we can add GUI controls such as progress-bars, not just simple text labels...</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>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/checking-status-of-warning-messages-in-mex/feed</wfw:commentRss>
			<slash:comments>0</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 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 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>
	</channel>
</rss>
