<?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>Peter Li &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/peter-li/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Thu, 15 Mar 2012 18:11:23 +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>Matlab&#039;s internal memory representation</title>
		<link>https://undocumentedmatlab.com/articles/matlabs-internal-memory-representation?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlabs-internal-memory-representation</link>
					<comments>https://undocumentedmatlab.com/articles/matlabs-internal-memory-representation#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 15 Mar 2012 18:11:23 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Memory]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Peter Li]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2798</guid>

					<description><![CDATA[<p>Matlab's internal memory structure is explored and discussed. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlabs-internal-memory-representation">Matlab&#039;s internal memory representation</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/internal-matlab-memory-optimizations" rel="bookmark" title="Internal Matlab memory optimizations">Internal Matlab memory optimizations </a> <small>Copy-on-write and in-place data manipulations are very useful Matlab performance improvement techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/couple-of-bugs-and-workarounds" rel="bookmark" title="A couple of internal Matlab bugs and workarounds">A couple of internal Matlab bugs and workarounds </a> <small>A couple of undocumented Matlab bugs have simple workarounds. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage" rel="bookmark" title="Profiling Matlab memory usage">Profiling Matlab memory usage </a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-internal-java-class-members" rel="bookmark" title="Accessing internal Java class members">Accessing internal Java class members </a> <small>Java inner classes and enumerations can be used in Matlab with a bit of tweaking. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>Once again I&#8217;d like to welcome guest blogger <a target="_blank" rel="nofollow" href="http://absurdlycertain.blogspot.com/">Peter Li</a>. Peter wrote about <a target="_blank" href="/articles/matlab-mex-in-place-editing/">Matlab Mex in-place editing</a> last month. Today, Peter pokes around in Matlab&#8217;s internal memory representation to the greater good and glory of Matlab Mex programming.</i><br />
<b><i>Disclaimer: The information in this article is provided for informational purposes only.  Be aware that poking into Matlab&#8217;s internals is not condoned or supported by MathWorks, and is not recommended for any regular usage.  Poking into memory has the potential to crash your computer so save your data!  Moreover, be advised (as the text below will show) that the information is highly prone to change without any advance notice in future Matlab releases, which could lead to very adverse effects on any program that relies on it. On the scale of undocumented Matlab topics, this practically breaks the scale, so be EXTREMELY careful when using this.</i></b><br />
A few weeks ago I <a target="_blank" href="/articles/matlab-mex-in-place-editing/">discussed</a> Matlab&#8217;s copy-on-write mechanism as part of my discussion of editing Matlab arrays in-place.  Today I want to explore some behind-the-scenes details of how the copy-on-write mechanism is implemented.  In the process we will learn a little about Matlab&#8217;s internal array representation.  I will also introduce some simple tools you can use to explore more of Matlab&#8217;s internals.  I will only cover basic information, so there are plenty more details left to be filled in by others who are interested.</p>
<h3 id="Copy-on-write">Brief review of copy-on-write and mxArray</h3>
<p>Copy-on-write is Matlab&#8217;s mechanism for avoiding unnecessary duplication of data in memory.  To implement this, Matlab needs to keep track internally of which sets of variables are copies of each other.  As described in <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f21585.html">MathWorks&#8217;s article</a>, &#8220;<i>the Matlab language works with a single object type: the Matlab array. All Matlab variables (including scalars, vectors, matrices, strings, cell arrays, structures, and objects) are stored as Matlab arrays. In C/C++, the Matlab array is declared to be of type <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/apiref/mxarray.html"><code>mxArray</code></a></i>&#8220;. This means that <code>mxArray</code> defines how Matlab lays out all the information about an array (its Matlab data type, its size, its data, etc.) in memory.  So understanding Matlab&#8217;s internal array representation basically boils down to understanding <code>mxArray</code>.<br />
Unfortunately, MathWorks also tells us that &#8220;<i><code>mxArray</code> is a C language <a target='_blank' rel='nofollow' href='http://en.wikipedia.org/wiki/Opaque_pointer'>opaque type</a></i>&#8220;. This means that MathWorks does not expose the organization of <code>mxArray</code> to users (i.e. Matlab or Mex programmers).  Instead, MathWorks defines <code>mxArray</code> internally, and allows users to interact with it only through an API, a set of functions that know how to handle <code>mxArray</code> in their back end.  So, for example, a Mex programmer does not get the dimensions of an <code>mxArray</code> by directly accessing the relevant field in memory.  Instead, the Mex programmer only has a pointer to the <code>mxArray</code>, and passes this pointer into an API function that knows where in memory to find the requested information and then passes the result back to the programmer.<br />
This is generally a good thing: the API provides an abstraction layer between the programmer and the memory structures so that if MathWorks needs to change the back end organization (to add a new feature for example), we programmers do not need to modify our code; instead MathWorks just updates the API to reflect the new internal organization.  On the other hand, being able to look into the internal structure of <code>mxArray</code> on occasion can help us understand how Matlab works, and can help us write more efficient code if we are careful as in the example of editing arrays in-place.<br />
So how do we get a glimpse inside <code>mxArray</code>?  The first step is simply to find the region of memory where the <code>mxArray</code> lives: its beginning and end.  Finding where in memory the <code>mxArray</code> begins is pretty easy: it is given by its pointer value.  Here is a simple Mex function that takes a Matlab array as input and prints its memory address:</p>
<pre lang='c'>
/* printaddr.cpp */
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
   if (nrhs < 1) mexErrMsgTxt("One input required.");
   printf("%p\n", prhs[0]);
}
</pre>
<p>This function is nice as it prints the address in a standard hexadecimal format.  The same information can also be received directly in Matlab (i.e., without needing <i><b>printaddr</b></i>), using the undocumented <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/15485#34519"><i><b>format debug</b></i> command</a> (here's <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/15988">another reference</a>):</p>
<pre lang='matlab'>
>> format debug
>> A = 1:10
A =
Structure address = 7fc3b8869ae0
m = 1
n = 10
pr = 7fc44922c890
pi = 0
     1     2     3     4     5     6     7     8     9    10
>> printaddr(A)
7fc3b8869ae0
</pre>
<p>To play with this further from within Matlab however, it&#8217;s nice to have the address returned to us as a 64-bit unsigned integer; here&#8217;s a Mex function that does that:</p>
<pre lang='c'>
/* getaddr.cpp */
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
   if (nrhs < 1) mexErrMsgTxt("One input required.");
   plhs[0] = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL);
   unsigned long *out = static_cast<unsigned long *>(mxGetData(plhs[0]));
   out[0] = (unsigned long) prhs[0];
}
</pre>
<p>Here&#8217;s <i><b>getaddr</b></i> in action:</p>
<pre lang='matlab'>
>> getaddr(A)
ans =
           139870853618400
% And using pure Matlab:
>> hex2dec('7f36388b5ae0')  % output of printaddr or format debug
ans =
           139870853618400
</pre>
<p>So now we know where to find our array in memory.  With this information we can already learn a lot.  To make our exploration a little cleaner though, it would be nice to know where the array ends in memory too, in other words we would like to know the size of the <code>mxArray</code>.</p>
<h3 id="Structure">Finding the structure of mxArray</h3>
<p>The first thing to understand is that the amount of memory taken by an <code>mxArray</code> does not have anything to do with the dimensions of the array in Matlab.  So a 1&#215;1 Matlab array and a 100&#215;100 Matlab array have the same size <code>mxArray</code> representation in memory.  As you will know if you have experience programming in Mex, this is simply because the Matlab array&#8217;s data contents are not stored directly within <code>mxArray</code>.  Instead, <code>mxArray</code> only stores a pointer to another memory location where the actual data reside.  This is fine; the internal information we want to poke into is all still in <code>mxArray</code>, and it is easy to get the pointer to the array&#8217;s data contents using the API functions <i>mxGetData</i> or <i>mxGetPr</i>.<br />
So we are still left with trying to figure out the size of <code>mxArray</code>.  There are a couple paths forward.  First I want to talk about a historical tool that used to make a lot of this internal information easily available.  This was a function called <i>headerdump</i>, by Peter Boetcher (described <a target="_blank" rel="nofollow" href="http://www.mit.edu/~pwb/matlab/">here</a> and <a target="_blank" rel="nofollow" href="http://groups.google.com/group/comp.soft-sys.matlab/browse_thread/thread/c241d8821fb90275">here</a>).  <i>headerdump</i> was created for exactly the goal we are currently working towards: to understand Matlab&#8217;s copy-on-write mechanism.  Unfortunately, as Matlab has evolved, newer versions have incrementally broken this useful tool.  So our goal here is to create a replacement.  Still, we can learn a lot from the earlier work.<br />
One of the things that helped people figure out Matlab&#8217;s internals in the past is that in older versions of Matlab <code>mxArray</code> is not a completely opaque type.  Even in recent versions up through at least R2010a, if you look into $MATLAB/extern/include/matrix.h you can find a definition of <code>mxArray_tag</code> that looks something like this:</p>
<pre lang='c'>
/* R2010a */
struct mxArray_tag {
   void  *reserved;
   int    reserved1[2];
   void  *reserved2;
   size_t  number_of_dims;
   unsigned int reserved3;
   struct {
       unsigned int  flag0  : 1;
       unsigned int  flag1  : 1;
       unsigned int  flag2  : 1;
       unsigned int  flag3  : 1;
       unsigned int  flag4  : 1;
       unsigned int  flag5  : 1;
       unsigned int  flag6  : 1;
       unsigned int  flag7  : 1;
       unsigned int  flag7a : 1;
       unsigned int  flag8  : 1;
       unsigned int  flag9  : 1;
       unsigned int  flag10 : 1;
       unsigned int  flag11 : 4;
       unsigned int  flag12 : 8;
       unsigned int  flag13 : 8;
   }   flags;
   size_t reserved4[2];
   union {
       struct {
           void  *pdata;
           void  *pimag_data;
           void  *reserved5;
           size_t reserved6[3];
       }   number_array;
   }   data;
};
</pre>
<p>This is what you could call murky or obfuscated, but not completely opaque.  The fields mostly have unhelpful names like &#8220;reserved&#8221;, but on the other hand we at least have a sense for what fields there are and their layout.<br />
A more informative (yet unofficial) definition was <a target="_blank" rel="nofollow" href="http://groups.google.com/group/comp.soft-sys.matlab/browse_thread/thread/b8dbd91953c494fb">provided</a> by James Tursa and Peter Boetcher:</p>
<pre lang='c'>
#include "mex.h"
/* Definition of structure mxArray_tag for debugging purposes. Might not be fully correct
 * for Matlab 2006b or 2007a, but the important things are. Thanks to Peter Boettcher.
 */
struct mxArray_tag {
  const char *name;
  mxClassID class_id;
  int vartype;
  mxArray    *crosslink;
  int      number_of_dims;
  int      refcount;
  struct {
    unsigned int    scalar_flag : 1;
    unsigned int    flag1 : 1;
    unsigned int    flag2 : 1;
    unsigned int    flag3 : 1;
    unsigned int    flag4 : 1;
    unsigned int    flag5 : 1;
    unsigned int    flag6 : 1;
    unsigned int    flag7 : 1;
    unsigned int    private_data_flag : 1;
    unsigned int    flag8 : 1;
    unsigned int    flag9 : 1;
    unsigned int    flag10 : 1;
    unsigned int    flag11 : 4;
    unsigned int    flag12 : 8;
    unsigned int    flag13 : 8;
  }   flags;
  int  rowdim;
  int  coldim;
  union {
    struct {
      double  *pdata;       // original: void*
      double  *pimag_data;  // original: void*
      void    *irptr;
      void    *jcptr;
      int     nelements;
      int     nfields;
    }   number_array;
    struct {
      mxArray **pdata;
      char    *field_names;
      void    *dummy1;
      void    *dummy2;
      int     dummy3;
      int     nfields;
    }   struct_array;
    struct {
      void  *pdata;  /*mxGetInfo*/
      char  *field_names;
      char  *name;
      int   checksum;
      int   nelements;
      int   reserved;
    }  object_array;
  }   data;
};
</pre>
<p>For comparison, here is another definition from an earlier version of Matlab.</p>
<pre lang='c'>
/* R11 aka Matlab 5.0 (1999) */
struct mxArray_tag {
  char name[mxMAXNAM];
  int  class_id;
  int  vartype;
  mxArray *crosslink;
  int  number_of_dims;
  int  nelements_allocated;
  int  dataflags;
  int  rowdim;
  int  coldim;
  union {
    struct {
      void *pdata;
      void *pimag_data;
      void *irptr;
      void *jcptr;
      int   reserved;
      int   nfields;
    }   number_array;
  }   data;
};
</pre>
<p>I took this R11 definition from the source code to <i>headerdump</i> (specifically, from <i>mxinternals.h</i>, which also has <code>mxArray_tag</code> definitions for R12 (Matlab 6.0) and R13 (Matlab 6.5)), and you can see that it is much more informative, because many fields have been given useful names thanks to the work of Peter Boetcher and others.  Note also that the definition from this old version of Matlab is quite different from the version from R2010a.<br />
At this point, if you are running a much earlier version of Matlab like R11 or R13, you can break off from the current article and start playing around with <i>headerdump</i> directly to try to understand Matlab&#8217;s internals.  For more recent versions of Matlab, we have more work to do.  Getting back to our original goal, if we take the <code>mxArray_tag</code> definition from R2010a and run <i>sizeof</i>, we get an answer for the amount of memory taken up by an <code>mxArray</code> in R2010a: <b>104 bytes</b>.</p>
<h3 id="Size">Determining the size of mxArray</h3>
<p>It was nice to derive the size of <code>mxArray</code> from actual MathWorks code, but unfortunately this information is no longer available as of R2011a.  Somewhere between R2010a and R2011a, MathWorks stepped up their efforts to make <code>mxArray</code> completely opaque.  So we should find another way to get the size of <code>mxArray</code> for current and future Matlab versions.<br />
One ugly trick that works is to create many new arrays quickly and see where their starting points end up in memory:</p>
<pre lang='matlab'>
>> A = num2cell(1:100)';
>> addrs = sort(cellfun(@getaddr, A));
</pre>
<p>What we did here is create 100 new arrays, and then get all their memory addresses in sorted order.  Now we can take a look at how far apart these new arrays ended up in memory:</p>
<pre lang='matlab'>
>> semilogy(diff(addrs));
</pre>
<p>The resulting plot will look different each time you run this; it is not really predictable where Matlab will put new arrays into memory.  Here is an example from my system:<br />
<center><figure style="width: 483px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" alt="Plot of memory addresses" src="https://undocumentedmatlab.com/images/mxArray_memory.png" title="Plot of memory addresses" width="483" height="381" /><figcaption class="wp-caption-text">Plot of memory addresses</figcaption></figure></center><br />
Your results may look different, and you might have to increase the number of new arrays from 100 to 1000 to get the qualitative result, but the important feature of this plot is that there is a minimum distance between new arrays of about 10<sup>2</sup>.  In fact, if we just go straight for this minimum distance:</p>
<pre lang='matlab'>
>> min(diff(addrs))
ans =
            104
</pre>
<p>we find that although <code>mxArray</code> has gone completely opaque from R2010a to R2011a, the full size of <code>mxArray</code> in memory has stayed the same: 104 bytes.</p>
<h3 id="Dump">Dumping mxArray from memory</h3>
<p>We now have all the information we need to start looking into Matlab&#8217;s array representation.  There are many tools available that allow you to browse memory locations or dump memory contents to disk.  For our purposes though, it is nice to be able to do everything from within Matlab.  Therefore I introduce a simple tool that prints memory locations into the Matlab console:</p>
<pre lang='c'>
/* printmem.cpp */
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  if (nrhs < 1 || !mxIsUint64(prhs[0]) || mxIsEmpty(prhs[0]))
    mexErrMsgTxt("First argument must be a uint64 memory address");
  unsigned long *addr = static_cast<unsigned long *>(mxGetData(prhs[0]));
  unsigned char *mem = (unsigned char *) addr[0];
  if (nrhs < 2 || !mxIsDouble(prhs[1]) || mxIsEmpty(prhs[1]))
    mexErrMsgTxt("Second argument must be a double-type integer byte size.");
  unsigned int nbytes = static_cast<unsigned int>(mxGetScalar(prhs[1]));
  for (int i = 0; i < nbytes; i++) {
    printf("%.2x ", mem[i]);
    if ((i+1) % 16 == 0) printf("\n");
 }
 printf("\n");
}
</pre>
<p>Here is how you use it in Matlab:</p>
<pre lang='matlab'>
>> A = 0;
>> printmem(getaddr(A), 104)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00
00 00 00 00 01 02 00 00 01 00 00 00 00 00 00 00
01 00 00 00 00 00 00 00 70 fa 33 df 6f 7f 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00
</pre>
<p>And there you have it: the inner guts of <code>mxArray</code> laid bare.  I have printed each byte as a two character hexadecimal value, as is standard, so there are 16 bytes printed per row.</p>
<h3 id="">What does it mean?</h3>
<p>So now we have 104 bytes of Matlab internals to dig into.  We can start playing with this with a few simple examples:</p>
<pre>
>> A = 0; B = 1;
>> printmem(getaddr(A), 104)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00
00 00 00 00 01 02 00 00 01 00 00 00 00 00 00 00
01 00 00 00 00 00 00 00 <span style="background-color:#e6b8af;">c0 b0 27 df 6f 7f</span> 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00
>> printmem(getaddr(B), 104)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00
00 00 00 00 01 02 00 00 01 00 00 00 00 00 00 00
01 00 00 00 00 00 00 00 <span style="background-color:#e6b8af;">70 fa 33 df 6f 7f</span> 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00
</pre>
<p>
In this and subsequent examples, I will highlight bytes that are different or that are of interest.  What we can see from this example is that although arrays A and B have different content, almost nothing is different between their <code>mxArray</code> representations.  What is different, is the memory address stored in the highlighted bytes.  This confirms our earlier assertion that <code>mxArray</code> does not store the array contents, but only a pointer to the content location.<br />
Now let us try to figure out some of the other fields:</p>
<pre>
>> A = 1:3; B = 1:10; C = (1:10)';
>> printmem(getaddr(A), 64)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 00 00 00 00 00
00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 <span style="background-color:#e6b8af;">01</span> 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">03</span> 00 00 00 00 00 00 00 60 80 22 df 6f 7f 00 00
>> printmem(getaddr(B), 64)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 00 00 00 00 00
00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 <span style="background-color:#e6b8af;">01</span> 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">0a</span> 00 00 00 00 00 00 00 80 83 29 df 6f 7f 00 00
>> printmem(getaddr(C), 64)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 00 00 00 00 00
00 00 00 00 00 <span style="background-color:#a4c2f4;">02</span> 00 00 <span style="background-color:#e6b8af;">0a</span> 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">01</span> 00 00 00 00 00 00 00 80 83 29 df 6f 7f 00 00
</pre>
<p>
(Note that this time I only printed the first four lines of each array as this is where the interesting differences are for this example.)<br />
In <span style="background-color:#e6b8af;">red</span> I highlighted the bytes in each array that give its number of rows and columns (note that hexadecimal 0a is 10 in decimal).  In <span style="background-color:#a4c2f4;">blue</span> I highlighted areas that store the value &#8220;02&#8221;, which could be the location for storing the number of dimensions.  Let us look into this more:</p>
<pre>
>> A = rand([3 3 3]);
>> printmem(getaddr(A), 64)
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 <span style="background-color:#e6b8af;">03</span> 00 00 00 00 00 00 00
00 00 00 00 00 02 00 00 <span style="background-color:#e6b8af;">30 4a 3f df 6f 7f</span> 00 00
<span style="background-color:#e6b8af;">09</span> 00 00 00 00 00 00 00 b0 d3 24 df 6f 7f 00 00
</pre>
<p>
Two interesting results here:  The first highlighted region changed from 02 to 03, so this must be the place where <code>mxArray</code> indicates a 3-dimensional array rather than 2D.  Another important thing also changed though: we can see in the second highlighted region that there is a new memory address stored where we used to find the number of rows.  And in the third highlighted region we now have the number 09 instead of the number of columns.<br />
Clearly, Matlab has a different way of representing a 2D matrix versus arrays of higher dimension such as 3D.  In the 2D case, <code>mxArray</code> simply holds the nrows and ncols directly, but for a higher dimension case we hold only the number of dimensions (03), the total number of elements (09), and a pointer to another memory location (0x7f6fdf3f4a30) which holds the array of sizes for each dimension.</p>
<h3 id="COW">The copy-on-write mechanism</h3>
<p>Finally, we are in a position to understand how Matlab internally implements copy-on-write:</p>
<pre>
>> A = 1:10;
>> printmem(getaddr(A), 64);
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00
00 00 00 00 00 02 00 00 01 00 00 00 00 00 00 00
0a 00 00 00 00 00 00 00 90 f3 24 df 6f 7f 00 00
>> B = A;
>> printaddr(B);
0x7f6f4c7b6810
>> printmem(getaddr(A), 64);
<span style="background-color:#e6b8af;">10 68 7b 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">10 68 7b 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00
00 00 00 00 00 02 00 00 01 00 00 00 00 00 00 00
0a 00 00 00 00 00 00 00 <span style="background-color:#a4c2f4;">90 f3 24 df 6f 7f</span> 00 00
</pre>
<p>
What we see is that by setting B = A, we change the internal representation of A itself.  Two new memory address pointers are added to the <code>mxArray</code> for A.  As it turns out, both of these point to the address for array B, which makes sense; this is how Matlab internally keeps track of arrays that are copies of each other.  Note that because byte order is <a target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Endianness">little-endian</a>, the memory addresses from <i><b>printmem</b></i> are byte-wise, i.e. every two characters, reversed relative to the address from <i><b>printaddr</b></i>.<br />
We can also look into array B:</p>
<pre>
>> printmem(getaddr(B), 64);
<span style="background-color:#e6b8af;">f0 41 7a 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">f0 41 7a 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00
00 00 00 00 00 02 00 00 01 00 00 00 00 00 00 00
0a 00 00 00 00 00 00 00 <span style="background-color:#a4c2f4;">90 f3 24 df 6f 7f</span> 00 00
>> printaddr(A);
<span style="background-color:#e6b8af;">0x7f6f4c7a41f0</span>
</pre>
<p>
As I have highlighted, there are two interesting points here.  First the red highlights show that array B has pointers back to array A.  Second the blue highlight shows that the Matlab data for array B actually just points back to the same memory as the data for array A (the values 1:10).<br />
Finally, we would like to understand why there are two pointers added.  Let us see what happens if we add a third linked variable:</p>
<pre>
>> C = B;
>> printaddr(A); printaddr(B); printaddr(C);
<span style="background-color:#e6b8af;">0x7f6f4c7a41f0</span>
<span style="background-color:#a4c2f4;">0x7f6f4c7b6810</span>
<span style="background-color:#00ff00;">0x7f6f4c7b69b0</span>
>> printmem(getaddr(A), 32)
<span style="background-color:#00ff00;">b0 69 7b 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#a4c2f4;">10 68 7b 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00
>> printmem(getaddr(B), 32)
<span style="background-color:#e6b8af;">f0 41 7a 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#00ff00;">b0 69 7b 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00
>> printmem(getaddr(C), 32)
<span style="background-color:#a4c2f4;">10 68 7b 4c 6f 7f</span> 00 00 06 00 00 00 00 00 00 00
<span style="background-color:#e6b8af;">f0 41 7a 4c 6f 7f</span> 00 00 02 00 00 00 00 00 00 00
</pre>
<p>
So it turns out that Matlab keeps track of a set of linked variables with a kind of cyclical, doubly-linked list structure; array A is linked to B in the forward direction and is also linked to C in the reverse direction by looping back around, etc.  The cyclical nature of this makes sense, as we need to be able to start from any of A, B, or C and find all the linked arrays.  But it is still not entirely clear why the list needs to be cyclical AND linked in both directions.  In fact, in earlier versions of Matlab this cyclical list was only singly-linked.</p>
<h3 id="Conclusions">Conclusions</h3>
<p>Obviously there is a lot more to <code>mxArray</code> and Matlab internals than what we have delved into here.  Still, with this basic introduction I hope to have whet your appetite for understanding more about Matlab internals, and provided some simple tools to help you explore.  I want to reiterate that in general MathWorks&#8217;s approach of an opaque <code>mxArray</code> type with access abstracted through an API layer is a good policy.  The last thing you would want to do is take the information here and write a bunch of code that relies on the structure of <code>mxArray</code> to work; next time MathWorks needs to add a new feature and change <code>mxArray</code>, all your code will break.  So in general we are all better off playing within the API that MathWorks provides.  And remember: poking into memory can crash your computer, so save your data!<br />
On the other hand, occasionally there are cases, like in-place editing, where it is useful to push the capabilities of Matlab a little beyond what MathWorks envisioned.  In these cases, having an understanding of Matlab&#8217;s internals can be critical, for example in understanding how to avoid conflicting with copy-on-write.  Therefore I hope the information presented here will prove useful.  Ideally, someone will be motivated to take this starting point and repair some of the tools like <i>headerdump</i> that made Matlab&#8217;s internal workings more transparent in the past.  I believe that having more of this information out in the Matlab community is good for the community as a whole.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlabs-internal-memory-representation">Matlab&#039;s internal memory representation</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/internal-matlab-memory-optimizations" rel="bookmark" title="Internal Matlab memory optimizations">Internal Matlab memory optimizations </a> <small>Copy-on-write and in-place data manipulations are very useful Matlab performance improvement techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/couple-of-bugs-and-workarounds" rel="bookmark" title="A couple of internal Matlab bugs and workarounds">A couple of internal Matlab bugs and workarounds </a> <small>A couple of undocumented Matlab bugs have simple workarounds. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage" rel="bookmark" title="Profiling Matlab memory usage">Profiling Matlab memory usage </a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-internal-java-class-members" rel="bookmark" title="Accessing internal Java class members">Accessing internal Java class members </a> <small>Java inner classes and enumerations can be used in Matlab with a bit of tweaking. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlabs-internal-memory-representation/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab mex in-place editing</title>
		<link>https://undocumentedmatlab.com/articles/matlab-mex-in-place-editing?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-mex-in-place-editing</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-mex-in-place-editing#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 08 Feb 2012 17:00:25 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Memory]]></category>
		<category><![CDATA[Mex]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Peter Li]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=2699</guid>

					<description><![CDATA[<p>Editing Matlab arrays in-place can be an important technique for optimizing calculations. This article shows how to do it using Mex.  </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-mex-in-place-editing">Matlab mex in-place editing</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/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>
<li><a href="https://undocumentedmatlab.com/articles/internal-matlab-memory-optimizations" rel="bookmark" title="Internal Matlab memory optimizations">Internal Matlab memory optimizations </a> <small>Copy-on-write and in-place data manipulations are very useful Matlab performance improvement techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-private-object-properties" rel="bookmark" title="Accessing private object properties">Accessing private object properties </a> <small>Private properties of Matlab class objects can be accessed (read and write) using some undocumented techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlabs-internal-memory-representation" rel="bookmark" title="Matlab&#039;s internal memory representation">Matlab&#039;s internal memory representation </a> <small>Matlab's internal memory structure is explored and discussed. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to welcome Matlab Mex power-user <a target="_blank" rel="nofollow" href="http://absurdlycertain.blogspot.com/">Peter Li</a> to a first in a short series of articles about undocumented aspects of Mex programing</i><br />
Editing Matlab arrays in-place can be an important technique for optimizing calculations, especially when handling data that use large blocks of memory.  The Matlab language itself has some <a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data/">limited support for in-place editing</a>, but when we are really concerned with speed we often turn to writing C/C++ extensions using the Mex interface.  Unfortunately, editing arrays in-place from Mex extensions is not officially supported in Matlab, and doing it incorrectly can cause data inconsistencies or can even cause Matlab to crash.  In this article, I will introduce the problem and show a simple solution that exhibit the basic implementation details of Matlab&#8217;s internal copy-on-write mechanism.</p>
<h3 id="Motivation">Why edit in-place?</h3>
<p>To demonstrate the techniques in this article, I use the <i>fast_median</i> function, which is part of <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/29453-nthelement">my nth_element package</a> on Matlab&#8217;s File Exchange.  You can download the package and play with the code if you want.  The examples are fairly self-explanatory, so if you do not want to try the code you should be okay just following along.<br />
Let us try a few function calls to see how editing in-place can save time and memory:</p>
<pre lang='matlab'>
>> A = rand(100000000, 1);
>> tic; median(A); toc
Elapsed time is 4.122654 seconds.
>> tic; fast_median(A); toc
Elapsed time is 1.646448 seconds.
>> tic; fast_median_ip(A); toc
Elapsed time is 0.927898 seconds.
</pre>
<p>If you try running this, be careful not to make A too large; tune the example according to the memory available on your system. In terms of the execution time for the different functions, your mileage may vary depending on factors such as: your system, what Matlab version you are running, and whether your test data is arranged in a single vector or a multicolumn array.<br />
This example illustrates a few general points: first, <i>fast_median</i> is significantly faster than Matlab&#8217;s <i><b>native</b></i> median function. This is because <i>fast_median</i> uses a more efficient algorithm; see the nth_element page for more details.  Besides being a shameless plug, this demonstrates why we might want to write a Mex function in the first place: rewriting the median function in pure Matlab would be slow, but using C++ we can significantly improve on the status quo.<br />
The second point is that the in-place version, <i>fast_median_ip</i>, yields an additional speed improvement.  What is the difference?  Let us look behind the scenes; here are the CPU and memory traces from my system monitor after running the above:<br />
<center><figure style="width: 377px" class="wp-caption alignleft"><img decoding="async" alt="Memory and CPU usage for median() vs. fast_median_ip()" src="https://undocumentedmatlab.com/images/median_vs_fast_median_ip.png" title="Memory and CPU usage for median() vs. fast_median_ip()" width="377" height="425"/><figcaption class="wp-caption-text">Memory and CPU usage for <i><b>median</b></i> vs. <i>fast_median_ip</i></figcaption></figure></center><br />
You can see four spikes in CPU use, and some associated changes in memory allocation:<br />
The first spike in CPU is when we created the test data vector; memory use also steps up at that time.<br />
The second CPU spike is the largest; that is Matlab&#8217;s median function.  You can see that over that period memory use stepped up again, and then stepped back down; the median function makes a copy of the entire input data, and then throws its copy away when it is finished; this is expensive in terms of time and resources.<br />
The <i>fast_median</i> function is the next CPU spike; it has a similar step up and down in memory use, but it is much faster.<br />
Finally, in the case of <i>fast_median_ip</i> we see something different; there is a spike in CPU use, but memory use stays flat; the in-place version is faster and more memory efficient because it does not make a copy of the input data.</p>
<div class="" style="width: 100%; overflow: auto;"></div>
<p>There is another important difference with the in-place version; it modifies its input array.  This can be demonstrated simply:</p>
<pre lang='matlab'>
>> A = randi(100, [10 1]);
>> A'
ans = 39    42    98    25    64    75     6    56    71    89
>> median(A)
ans = 60
>> fast_median(A)
ans = 60
>> A'
ans = 39    42    98    25    64    75     6    56    71    89
>> fast_median_ip(A)
ans = 60
>> A'
ans = 39     6    25    42    56    64    75    71    98    89
</pre>
<p>As you can see, all three methods get the same answer, but <i><b>median</b></i> and <i>fast_median</i> do not modify A in the workspace, whereas after running <i>fast_median_ip</i>, input array A has changed.  This is how the in-place method is able to run without using new memory; it operates on the existing array rather than making a copy.</p>
<h3 id="Pitfalls">Pitfalls with in-place editing</h3>
<p>Modifying a function&#8217;s input is common in many languages, but in Matlab there are only a few special conditions under which this is officially sanctioned.  This is not necessarily a bad thing; many people feel that modifying input data is bad programming practice and makes code harder to maintain.  But as we have shown, it can be an important capability to have if speed and memory use are critical to an application.<br />
Given that in-place editing is not officially supported in Matlab Mex extensions, what do we have to do to make it work?  Let us look at the normal, input-copying <i>fast_median</i> function as a starting point:</p>
<pre lang='cpp'>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
   mxArray *incopy = mxDuplicateArray(prhs[0]);
   plhs[0] = run_fast_median(incopy);
}
</pre>
<p>This is a pretty simple function (I have taken out a few lines of boiler plate input checking to keep things clean).  It relies on helper function <i>run_fast_median</i> to do the actual calculation, so the only real logic here is copying the input array <code>prhs[0]</code>.  Importantly, <i>run_fast_median</i> edits its inputs in-place, so the call to <i>mxDuplicateArray</i> ensures that the Mex function is overall well behaved, i.e. that it does not change its inputs.<br />
Who wants to be well behaved though?  Can we save time and memory just by taking out the input duplication step?  Let us try it:</p>
<pre lang='cpp'>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
   plhs[0] = run_fast_median(const_cast<mxArray *>(prhs[0]));  // </mxArray>
}
</pre>
<p>Very bad behavior; note that we cast the original <code>const mxArray*</code> input to a <code>mxArray*</code> so that the compiler will let us mess with it; naughty.<br />
But does this accomplish edit in-place for <i>fast_median</i>?  Be sure to save any work you have open and then try it:</p>
<pre lang='matlab'>
>> mex fast_median_tweaked.cpp
>> A = randi(100,[10 1]);
>> fast_median_tweaked(A)
ans = 43
</pre>
<p>Hmm, it looks like this worked fine.  But in fact there are subtle problems:</p>
<pre lang='matlab'>
>> A = randi(100,[10 1]);
>> A'
ans = 65    92    14    26    41     2    45    85    53     2
>> B = A;
>> B'
ans = 65    92    14    26    41     2    45    85    53     2
>> fast_median_tweaked(A)
ans = 43
>> A'
ans = 2     2    41    26    14    45    65    85    53    92
>> B'
ans = 2     2    41    26    14    45    65    85    53    92
</pre>
<p>Uhoh, spooky; we expected that running <i>fast_median_tweaked</i> would change input A, but somehow it has also changed B, even though B is supposed to be an independent copy.  Not good.  In fact, under some conditions this kind of uncontrolled editing in-place can crash the entire Matlab environment with a segfault.  What is going on?</p>
<h3 id="COW">Matlab&#8217;s copy-on-write mechanism</h3>
<p>The answer is that our simple attempt to edit in-place conflicts with Matlab&#8217;s internal copy-on-write mechanism.  Copy-on-write is an optimization built into Matlab to help avoid expensive copying of variables in memory (actually similar to what we are trying to accomplish with edit in-place).  We can see copy-on-write in action with some simple tests:<br />
<figure style="width: 393px" class="wp-caption alignright"><img decoding="async" alt="Matlab's Copy-on-Write memory and CPU usage" src="https://undocumentedmatlab.com/images/copy-on-write.png" title="Matlab's Copy-on-Write memory and CPU usage" width="393" height="466"/><figcaption class="wp-caption-text">Matlab's Copy-on-Write memory and CPU usage</figcaption></figure></p>
<div>
<pre lang='matlab'>
% Test #1: update, then copy
>> tic; A = zeros(100000000, 1); toc
Elapsed time is 0.588937 seconds.
>> tic; A(1) = 0; toc
Elapsed time is 0.000008 seconds.
>> tic; B = A; toc
Elapsed time is 0.000020 seconds.
% Test #2: copy, then update
>> clear
>> tic; A = zeros(100000000, 1); toc
Elapsed time is 0.588937 seconds.
>> tic; B = A; toc
Elapsed time is 0.000020 seconds.
>> tic; A(1) = 0; toc
Elapsed time is 0.678160 seconds.
</pre>
</div>
<p>In the first set of operations, time and memory are used to create A, but updating A and &#8220;copying&#8221; A into B take no memory and essentially no time.  This may come as a surprise since supposedly we have made an independent copy of A in B; why does creating B take no time or memory when A is clearly a large, expensive block?<br />
The second set of operations makes things more clear.  In this case, we again create A and then copy it to B; again this operation is fast and cheap.  But assigning into A at this point takes time and consumes a new block of memory, even though we are only assigning into a single index of A.  This is copy-on-write: Matlab tries to save you from copying large blocks of memory unless you need to.  So when you first assign B to equal A, nothing is copied; the variable B is simply set to point to the same memory location already used by A.  Only after you try to change A (or B), does Matlab decide that you really need to have two copies of the large array.<br />
There are some additional tricks Matlab does with copy-on-write.  Here is another example:</p>
<pre lang='matlab'>
>> clear
>> tic; A{1} = zeros(100000000, 1); toc
Elapsed time is 0.573240 seconds.
>> tic; A{2} = zeros(100000000, 1); toc
Elapsed time is 0.560369 seconds.
>> tic; B = A; toc
Elapsed time is 0.000016 seconds.
>> tic; A{1}(1) = 0; toc
Elapsed time is 0.690690 seconds.
>> tic; A{2}(1) = 0; toc
Elapsed time is 0.695758 seconds.
>> tic; A{1}(1) = 0; toc
Elapsed time is 0.000011 seconds.
>> tic; A{2}(1) = 0; toc
Elapsed time is 0.000004 seconds.
</pre>
<p>This shows that for the purposes of copy-on-write, different elements of cell array A are treated independently.  When we assign B equal to A, nothing is copied.  Then when we change any part of A{1}, that whole element must be copied over.  When we subsequently change A{2}, that whole element must also be copied over; it was not copied earlier.  At this point, A and B are truly independent of each other, as both elements have experienced copy-on-write, so further assignments into either A or B are fast and require no additional memory.<br />
Try playing with some struct arrays and you will find that copy-on-write also works independently for the elements of structs.</p>
<h3 id="mxUnshareArray">Reconciling edit in-place with copy-on-write: mxUnshareArray</h3>
<p>Now it is clear why we cannot simply edit arrays in-place from Mex functions; not only is it naughty, it fundamentally conflicts with copy-on-write.  Naively changing an array in-place can inadvertently change other variables that are still waiting for a copy-on-write, as we saw above when <i>fast_median_tweaked</i> inadvertently changed B in the workspace. This is, in the best case, an unmaintainable mess.  Under more aggressive in-place editing, it can cause Matlab to crash with a segfault.<br />
Luckily, there is a simple solution, although it requires calling internal, undocumented Matlab functions.<br />
Essentially what we need is a Mex function that can be run on a Matlab array that will do the following:</p>
<ol>
<li>Check whether the current array is sharing data with any other arrays that are waiting for copy-on-write.</li>
<li>If the array is shared, it must be unshared; the underlying memory must be copied and all the relevant pointers need to be fixed so that the array we want to work on is no longer accessible by anyone else.</li>
<li>If the array is not currently shared, simply proceed; the whole point is to avoid copying memory if we do not need to, so that we can benefit from the efficiencies of edit in-place.</li>
</ol>
<p>If you think about it, this is exactly the operation that Matlab needs to run internally when it is deciding whether an assignment operation requires a copy-on-write.  So it should come as no surprise that such a Mex function already exists in the form of a Matlab internal called <i>mxUnshareArray</i>.  Here is how you use it:</p>
<pre lang='cpp'>
extern "C" bool mxUnshareArray(mxArray *array_ptr, bool noDeepCopy);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
   mxUnshareArray(const_cast<mxArray *>(prhs[0]), true);  //</mxArray>
   plhs[0] = run_fast_median(const_cast<mxArray *>(prhs[0]));  //</mxArray>
}
</pre>
<p>This is the method actually used by <i>fast_median_ip</i> to efficiently edit in-place without risking conflicts with copy-on-write.  Of course, if the array turns out to need to be unshared, then you do not get the benefit of edit in-place because the memory ends up getting copied.  But at least things are safe and you get the in-place benefit as long as the input array is not being shared.</p>
<h3 id="Extra">Further topics</h3>
<p>The method shown here should allow you to edit normal Matlab numerical or character arrays in-place from Mex functions safely.  For a Mex function in C rather than C++, omit the &#8220;C&#8221; in the <code>extern</code> declaration and of course you will have to use C-style casting rather than <code>const_cast</code>.  If you need to edit cell or struct arrays in-place, or especially if you need to edit subsections of shared cell or struct arrays safely and efficiently while leaving the rest of the data shared, then you will need a few more tricks.  A good place to get started is <a target="_blank" rel="nofollow" href="http://www.mk.tu-berlin.de/Members/Benjamin/mex_sharedArrays">this article by Benjamin Schubert</a>.<br />
Unfortunately, over the last few years Mathworks seems to have decided to make it more difficult for users to access these kinds of internal methods to make our code more efficient.  So be aware of the risk that in some future version of Matlab this method will no longer work in its current form.<br />
Ultimately much of what is known about <i>mxUnshareArray</i> as well as the internal implementation details of how Matlab keeps track of which arrays are shared goes back to the work of Peter Boettcher, particularly his <a target="_blank" rel="nofollow" href="http://groups.google.com/group/comp.soft-sys.matlab/browse_thread/thread/c241d8821fb90275/">headerdump.c utility</a>.  Unfortunately, it appears that HeaderDump fails with Matlab releases >=R2010a, as Mathworks have changed some of the internal memory formats &#8211; perhaps some smart reader can pick up the work and adapt HeaderDump to the new memory format.<br />
In a future article, I hope to discuss headerdump.c and its relevance for copy-on-write and edit in-place, and some other related tools for the latest Matlab releases that do not support HeaderDump.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-mex-in-place-editing">Matlab mex in-place editing</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/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>
<li><a href="https://undocumentedmatlab.com/articles/internal-matlab-memory-optimizations" rel="bookmark" title="Internal Matlab memory optimizations">Internal Matlab memory optimizations </a> <small>Copy-on-write and in-place data manipulations are very useful Matlab performance improvement techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-private-object-properties" rel="bookmark" title="Accessing private object properties">Accessing private object properties </a> <small>Private properties of Matlab class objects can be accessed (read and write) using some undocumented techniques. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlabs-internal-memory-representation" rel="bookmark" title="Matlab&#039;s internal memory representation">Matlab&#039;s internal memory representation </a> <small>Matlab's internal memory structure is explored and discussed. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-mex-in-place-editing/feed</wfw:commentRss>
			<slash:comments>15</slash:comments>
		
		
			</item>
	</channel>
</rss>
