{"id":296,"date":"2011-11-14T16:48:00","date_gmt":"2011-11-14T21:48:00","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2011\/11\/14\/generating-c-code-from-your-matlab-algorithms\/"},"modified":"2016-08-04T08:44:44","modified_gmt":"2016-08-04T13:44:44","slug":"generating-c-code-from-your-matlab-algorithms","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2011\/11\/14\/generating-c-code-from-your-matlab-algorithms\/","title":{"rendered":"Generating C Code from Your MATLAB Algorithms"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>I am pleased to introduce guest blogger Arvind Ananthan. Arvind is the Product Marketing Manager for <a href=\"https:\/\/www.mathworks.com\/products\/matlab-coder\/\">MATLAB Coder<\/a> and <a href=\"https:\/\/www.mathworks.com\/products\/fixed\/\">Fixed-Point Toolbox<\/a>. His main focus in this post is to introduce basics of MATLAB Coder, talk about the workflow, its use cases, and show examples\r\n         of generated C code.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">A Brief History of MATLAB to C<\/a><\/li>\r\n         <li><a href=\"#2\">A Simple Example<\/a><\/li>\r\n         <li><a href=\"#7\">Detailed MATLAB Coder Worfklow<\/a><\/li>\r\n         <li><a href=\"#10\">Support for Dynamic Sizing<\/a><\/li>\r\n         <li><a href=\"#11\">Use Cases of MATLAB Coder<\/a><\/li>\r\n         <li><a href=\"#12\">Generating MEX Functions for Simulation Acceleration<\/a><\/li>\r\n         <li><a href=\"#16\">Vectorization and Code Generation<\/a><\/li>\r\n         <li><a href=\"#17\">Customizing and Optimizing the Generated Code<\/a><\/li>\r\n         <li><a href=\"#18\">Learning More About MATLAB Coder<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>A Brief History of MATLAB to C<a name=\"1\"><\/a><\/h3>\r\n   <p>In April, 2011, MathWorks introduced MATLAB Coder as a stand-alone product to generate C code from MATLAB code. This tool\r\n      lets user generate readable, portable, and customizable C code from their MATLAB algorithms.\r\n   <\/p>\r\n   <p>Many astute readers will notice that C code generation from MATLAB isn't really brand new - and that we've had this capability\r\n      to generate C code from MATLAB for quite some time now. Yes, that's true - we've been incubating this technology for quite\r\n      some time till we felt it was ready to debut as a stand alone tool. Here's a timeline of this technology over the past few\r\n      years:\r\n   <\/p>\r\n   <div>\r\n      <ul>\r\n         <li><b>2004<\/b> - Introduced the <i>Embedded MATLAB Function<\/i> block in Simulink\r\n         <\/li>\r\n         <li><b>2007<\/b> - Introduced the <tt>emlc<\/tt> function in Real-Time Workshop (now called Simulink Coder) to generate stand alone C from MATLAB\r\n         <\/li>\r\n         <li><b>2011<\/b> - Released MATLAB Coder, the first stand-alone product from MathWorks to generate portable and readable C code from MATLAB\r\n            code.\r\n         <\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>A Simple Example<a name=\"2\"><\/a><\/h3>\r\n   <p>Let me introduce the basics of using MATLAB Coder through a very simple example that multiplies two variables. Let's generate\r\n      C code from the following MATLAB function that multiplies two inputs:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">dbtype <span style=\"color: #A020F0\">simpleProduct.m<\/span><\/pre><pre style=\"font-style:oblique\">\r\n1     function c = simpleProduct(a,b) %#codegen\r\n2     c = a*b;\r\n<\/pre><p>To generate C code from this function using MATLAB Coder, I first have to specify the size and data types of my inputs - I\r\n      can do this through the MATLAB Coder UI (shown in the section below) where I specify my inputs as a [1x5] and [5x2] single\r\n      precision matrices, and subsequently generate the following C code:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">dbtype <span style=\"color: #A020F0\">simpleProduct.c<\/span><\/pre><pre style=\"font-style:oblique\">\r\n1     #include \"simpleProduct.h\"\r\n2     \r\n3     void simpleProduct(const real32_T a[5], const real32_T b[10], real32_T c[2])\r\n4     {\r\n5       int32_T i0;\r\n6       int32_T i1;\r\n7       for (i0 = 0; i0 &lt; 2; i0++) {\r\n8         c[i0] = 0.0F;\r\n9         for (i1 = 0; i1 &lt; 5; i1++) {\r\n10          c[i0] += a[i1] * b[i1 + 5 * i0];\r\n11        }\r\n12      }\r\n13    }\r\n\r\n<\/pre><p>MATLAB is a polymorphic language which means a single function, such as <tt>simpleProduct<\/tt>, can accept input arguments of different size and data types and output correct results. This function can behave as a simple\r\n      scalar product, a dot product, or a matrix multiplier depending on what inputs you pass.\r\n   <\/p>\r\n   <p>Languages like C are said to be &#8220;stongly typed,&#8221; which requires you to create a different version of a function for every\r\n      variation of input data size and types. Hence, when you write C code to implement <tt>simpleProduct<\/tt>, you have to know ahead of time the sizes and the data types of your inputs so you can implement the right variant.\r\n   <\/p>\r\n   <p>While MATLAB Coder helps you move from the highly flexible world of MATLAB to a strongly typed world of C, you still have\r\n      to specify all of the constraints C expects. You do this in MATLAB Coder by creating a MATLAB Coder project file (<tt>simpleProduct.prj<\/tt> in this case) where you can specify the  various code generation parameters including the sizes and data types of your inputs\r\n      as shown below.\r\n   <\/p>\r\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/296\/simpleProductPRJ.png\"> <\/p>\r\n   <p>You can also edit the default configuration parameters by clicking on the <i>'More Settings'<\/i> link which appears on the 'Build' tab of this project UI .\r\n   <\/p>\r\n   <p>In the example above, I turned off a few default options such as including comments in the generated code just so you can\r\n      see how compact the code is. You not only get the option to generate comments in the resulting C code, but also inlcude the\r\n      original MATLAB code as comments in the corresponding sections of the generated code. This helps with traceability of your\r\n      C code to your original algorithms.\r\n   <\/p>\r\n   <h3>Detailed MATLAB Coder Worfklow<a name=\"7\"><\/a><\/h3>\r\n   <p>The simple example above quickly illustrates the process of generating code with MATLAB coder and shows how the resulting\r\n      C code looks.\r\n   <\/p>\r\n   <p>Naturally, your real-world functions are going to be much more involved and may run into hundreds or even thousands of lines\r\n      of MATLAB Code. To help you handle that level of complexity, you would need an iterative process, like the 3-step workflow\r\n      described here, that guides you through the task of code generation incrementally:\r\n   <\/p>\r\n   <div>\r\n      <ol>\r\n         <li><b>Prepare:<\/b> First, prepare your code to ensure that you can indeed generate code from your MATLAB algorithm. The convenience of MATLAB\r\n            language doesn't map directly to the constrained behavior of C. You may have to re-write portions of your MATLAB code so it\r\n            uses the MATLAB language features that support this mapping from MATLAB to C.\r\n         <\/li>\r\n         <li><b>Test &amp; Verify:<\/b> Next, you generate a MEX function to test that your preparation step is correct. If the tool is successful in generating\r\n            a MEX function then you are ready to verify the results of this MEX function against the original MATLAB code. If not, you'd\r\n            have to iterate on the previous step till you can successfully generate a MEX function.\r\n         <\/li>\r\n         <li><b>Generate:<\/b> Finally, you generate C source code and further iterate upon your MATLAB code in order to control the look and feel or the\r\n            performance of your C code.You can also generate an optimized MEX function by turning off certain memory integrity checks\r\n            and debug options that could slow down its execution at this stage.\r\n         <\/li>\r\n      <\/ol>\r\n   <\/div>\r\n   <p>I'll now demonstrate this concept using a slightly more involved example. The following MATLAB code implements the Newton-Raphson\r\n      numerical technique for computing the n-th root of a real valued number.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">dbtype <span style=\"color: #A020F0\">newtonSearchAlgorithm.m<\/span><\/pre><pre style=\"font-style:oblique\">\r\n1     function [x,h] = newtonSearchAlgorithm(b,n,tol) %#codegen\r\n2     % Given, \"a\", this function finds the nth root of a\r\n3     % number by finding where: x^n-a=0.\r\n4     \r\n5         notDone = 1;\r\n6         aNew    = 0; %Refined Guess Initialization\r\n7         a       = 1; %Initial Guess\r\n8         count     = 0;\r\n9         h(1)=a;\r\n10        while notDone\r\n11            count = count+1;\r\n12            [curVal,slope] = fcnDerivative(a,b,n); %square\r\n13            yint = curVal-slope*a;\r\n14            aNew = -yint\/slope; %The new guess\r\n15            h(count)=aNew;\r\n16            if (abs(aNew-a) &lt; tol) %Break if it's converged\r\n17                notDone = 0;\r\n18            elseif count&gt;49 %after 50 iterations, stop\r\n19                notDone = 0;\r\n20                aNew = 0;\r\n21            else\r\n22                a = aNew;\r\n23            end\r\n24        end\r\n25        x = aNew;\r\n26        \r\n27    function [f,df] = fcnDerivative(a,b,n)\r\n28    % Our function is f=a^n-b and it's derivative is n*a^(n-1).\r\n29    \r\n30        f  = a^n-b;\r\n31        df = n*a^(n-1);\r\n\r\n<\/pre><p>Our first step towards generating C code from this file is to prepare it for code generation. For code generation, each variable\r\n      inside your MATLAB code must be intialized, which means specifying its size and data type. In this case, I'll choose to initialize\r\n      the variable <tt>h<\/tt> to a static maximum size, <tt>h = zeros(1,50)<\/tt>, as it doesn't grow beyond a length of 50 inside the <tt>for<\/tt> loop.\r\n   <\/p>\r\n   <p>You can invoke the code generation function using the GUI or the command line (through the <tt>codegen<\/tt> command). Without worrying about the details of this approach, let's look at the generated C code:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">dbtype <span style=\"color: #A020F0\">newtonSearchAlgorithmMLC.c<\/span><\/pre><pre style=\"font-style:oblique\">\r\n1     #include \"newtonSearchAlgorithmMLC.h\"\r\n2     \r\n3     void newtonSearchAlgorithmMLC(real_T b, real_T n, real_T tol, real_T *x, real_T\r\n4       h[50])\r\n5     {\r\n6       int32_T notDone;\r\n7       real_T a;\r\n8       int32_T count;\r\n9       real_T u1;\r\n10      real_T slope;\r\n11      notDone = 1;\r\n12      *x = 0.0;\r\n13      a = 1.0;\r\n14      count = -1;\r\n15      memset((void *)&amp;h[0], 0, 50U * sizeof(real_T));\r\n16      h[0] = 1.0;\r\n17      while (notDone != 0) {\r\n18        count++;\r\n19        u1 = n - 1.0;\r\n20        u1 = pow(a, u1);\r\n21        slope = n * u1;\r\n22        u1 = pow(a, n);\r\n23        *x = -((u1 - b) - slope * a) \/ slope;\r\n24        h[count] = *x;\r\n25        if (fabs(*x - a) &lt; tol) {\r\n26          notDone = 0;\r\n27        } else if (count + 1 &gt; 49) {\r\n28          notDone = 0;\r\n29          *x = 0.0;\r\n30        } else {\r\n31          a = *x;\r\n32        }\r\n33      }\r\n34    }\r\n\r\n<\/pre><p>The subfunction <tt>fcnDerivative<\/tt> is inlined in the generated C code.  You can choose to not inline the code by putting this command <tt>coder.inline('never')<\/tt> in the MATLAB file.\r\n   <\/p>\r\n   <h3>Support for Dynamic Sizing<a name=\"10\"><\/a><\/h3>\r\n   <p>If you have variable in your MATLAB code that needs to vary its size during execution, you can choose to deal with this in\r\n      three different ways in the generated C code:\r\n   <\/p>\r\n   <div>\r\n      <ol>\r\n         <li><b>Static allocation with fixed maximum size:<\/b> you can initialize variables to the maximum possible static size (like I did in the example above). In the generated code,\r\n            memory is prealloacted to this size.\r\n         <\/li>\r\n         <li><b>Variable sizing with maximum size allocation:<\/b> this option will declare the memory for the variable in the generated code to its maximum possible size, but you can dynamically\r\n            grow or shrink the variable size within this allocated maximum.\r\n         <\/li>\r\n         <li><b>Variable sizing with dynamic memory allocation:<\/b> this results in the generated code using <tt>malloc<\/tt> to allocate the memory for the variables that change in size during code execution.\r\n         <\/li>\r\n      <\/ol>\r\n   <\/div>\r\n   <p>The last two options can be enabled by turning on the <i><b>variable-sizing<\/b><\/i> feature in the configuration parameters. However, do remember that enabling this option also makes the resulting C code bigger\r\n      in size - so if you can avoid it, you can get much more compact and possibly more efficient code.\r\n   <\/p>\r\n   <h3>Use Cases of MATLAB Coder<a name=\"11\"><\/a><\/h3>\r\n   <p>The primary use of MATLAB Coder is to enable algorithm developers and system engineers working in MATLAB to quickly generate\r\n      readable and portable C code. The generated C code can be used in different ways supporting different workflows. Here are\r\n      a few use cases of MATLAB Coder:\r\n   <\/p>\r\n   <div>\r\n      <ol>\r\n         <li><b>Create standalone executables<\/b> from your algorithms for prototyping on a PC\r\n         <\/li>\r\n         <li><b>Speed up<\/b> your MATLAB algorithm code (or portions of it) by generating and executing the MEX functions\r\n         <\/li>\r\n         <li><b>Integrate<\/b> your MATLAB algorithms as C source code or compiled library with your hand-written software\r\n         <\/li>\r\n      <\/ol>\r\n   <\/div>\r\n   <p>I won't be talking about creating standalone executables or creating libraries from MATLAB Coder in this blog; I'll, however,\r\n      say a few words on generating MEX functions.\r\n   <\/p>\r\n   <h3>Generating MEX Functions for Simulation Acceleration<a name=\"12\"><\/a><\/h3>\r\n   <p>The MEX interface enables you to integrate C code into MATLAB. One common use of MEX is to speed up performance bottlenecks\r\n      in MATLAB code by re-writing them in C and executing them back in MATLAB as MEX functions. MATLAB Coder can save you time\r\n      and effort by automatically generating MEX functions from your MATLAB code (and allowing you to import legacy C code easily\r\n      as well).\r\n   <\/p>\r\n   <p>The speed-up you get through automatic MEX generation can vary quite a bit depending on the application. In some cases, you\r\n      may not get any speed up at all, or possibly even a slow-down, as MATLAB language has gotten quite smart and efficient in\r\n      computing many built-in functions by automatically taking advantage of processor specific routines (such as Intel Performance\r\n      Primitives) and multithreading to utilize multiple cores.\r\n   <\/p>\r\n   <p>A few guidelines that you can use to determine if your algorithm is a good candidate for speed-up with MEX are:<\/p>\r\n   <div>\r\n      <ul>\r\n         <li>your algorithm contains multiply nested <tt>for<\/tt> loops, and possibly handles state calculations (making each iteration dependent on the previous one)\r\n         <\/li>\r\n         <li>your MATLAB code is hard\/impossible to vectorize<\/li>\r\n         <li>most of the processing cycles in your algorithm are <b>not<\/b> spent on already optimized built-in functions such as <tt>fft<\/tt> or <tt>inv<\/tt>, etc.\r\n         <\/li>\r\n         <li>you don't rely heavily on toolbox functions (especially those unsupported for code generation) in your algorithms<\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>In these cases, you can expect to see a speed-up. Let's look at a realistic example that illustrates this concept.<\/p>\r\n   <p>The example I chose here is one that my colleague <a href=\"https:\/\/blogs.mathworks.com\/loren\/2008\/06\/25\/speeding-up-matlab-applications\/\">Sarah Zaranek<\/a> had highlighted in her guest blog on vectorization.\r\n   <\/p>\r\n   <p>I modified the original MATLAB script from that article into a function as only functions are supported by MATLAB Coder. The\r\n      other change that I made to the original script was to initialize the output variables <tt>subs<\/tt> and <tt>vals<\/tt> (as all variables in your code has to be defined\/intialized once when used with MATLAB Coder). And by turning on the variable\r\n      sizing feature (using dynamic memory allocation), I didn't have to preallocate it to a sufficiently large enough size to accomodate\r\n      its growth, which would use more memory (often a lot) than needed.\r\n   <\/p>\r\n   <p>The following statements create and use a MATLAB Coder configuration object with support for variable size arrays and dynamic\r\n      memory allocation to generate a MEX function.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #228B22\">% Create a MEX configuration object<\/span>\r\ncfg = coder.config(<span style=\"color: #A020F0\">'mex'<\/span>);\r\n<span style=\"color: #228B22\">% Turn on dynamic memory allocation<\/span>\r\ncfg.DynamicMemoryAllocation = <span style=\"color: #A020F0\">'AllVariableSizeArrays'<\/span>;\r\n<span style=\"color: #228B22\">% Generate MEX function<\/span>\r\ncodegen <span style=\"color: #A020F0\">-config<\/span> <span style=\"color: #A020F0\">cfg<\/span> <span style=\"color: #A020F0\">gridSpeedUpFcn<\/span> <span style=\"color: #A020F0\">-args<\/span> <span style=\"color: #A020F0\">{10}<\/span>\r\ndisp(<span style=\"color: #A020F0\">'MEX generation complete!'<\/span>)<\/pre><pre style=\"font-style:oblique\">Warning: There is no short path form of 'H:\\Documents\\LOREN\\MyJob\\Art of\r\nMATLAB' available. Short path names do not include embedded spaces. The\r\nshort path name feature may be disabled in your operating system. Short\r\npath names are required for successful code generation, therefore it may\r\nnot be possible to successfully complete the code generation process. To\r\navoid this problem, enable short path name support in your operating\r\nsystem, or do not attempt code generation in paths containing spaces. \r\nMEX generation complete!\r\n<\/pre><p>This generates a MEX function in the current folder. I'll use <tt>tic<\/tt>, and <tt>toc<\/tt> to estimate the execution times of the original MATLAB function and its MEX version.\r\n   <\/p>\r\n   <p>I run each function multiple times inside a <tt>for<\/tt> loop and use only the last few runs for our computation time calculation so we can minimize the effects of initialization\r\n      and caching.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">MToc = zeros(1,30);\r\nMexToc = zeros(1,30);\r\n<span style=\"color: #0000FF\">for<\/span> j = 1:30\r\n    tic; gridSpeedUpFcn(10);\r\n    MToc(j) = toc;\r\n<span style=\"color: #0000FF\">end<\/span>\r\n\r\n<span style=\"color: #0000FF\">for<\/span> j = 1:30\r\n    tic; gridSpeedUpFcn_mex(10);\r\n    MexToc(j) = toc;\r\n<span style=\"color: #0000FF\">end<\/span>\r\n\r\neff_M_time = mean(MToc(1,21:30));\r\neff_Mex_time = mean(MexToc(1,21:30));\r\n\r\ndisp([<span style=\"color: #A020F0\">'MATLAB code execution time (with nx=10): '<\/span>, num2str(eff_M_time)])\r\ndisp([<span style=\"color: #A020F0\">'MEX code executing time (with nx=10): '<\/span>, num2str(eff_Mex_time)])\r\n\r\ndisp([<span style=\"color: #A020F0\">' Speed up factor: '<\/span>, num2str(eff_M_time\/eff_Mex_time)]);<\/pre><pre style=\"font-style:oblique\">MATLAB code execution time (with nx=10): 0.31652\r\nMEX code executing time (with nx=10): 0.0027057\r\n Speed up factor: 116.9806\r\n<\/pre><p>The speed up we see in this example is more pronounced for larger values of <tt>nx<\/tt> (and would vary between different computers).\r\n   <\/p>\r\n   <h3>Vectorization and Code Generation<a name=\"16\"><\/a><\/h3>\r\n   <p>Sarah, in her blog <a href=\"https:\/\/blogs.mathworks.com\/loren\/2008\/06\/25\/speeding-up-matlab-applications\/\">article<\/a>, explains quite nicely on how to vectorize this code using <tt>meshgrid<\/tt> and <tt>ndgrid<\/tt> to explode the variables in support of vectorization, and get similar levels of speed up.\r\n   <\/p>\r\n   <p>Sarah paid a small price in code readability for her vectorization efforts, but a much larger price in memory consumption.\r\n      This points to a common trade-off when vectorizing MATLAB code: execution time vs. memory consumption. The temporary variables\r\n      which enable us to remove loops through matrix math are often very large, effectively limiting the number of iterations you\r\n      can take before running out of memory. For instance, if we run her algorithm for a 1,000x1,000 grid instead of a 100x100 grid,\r\n      we would create 9 double precision variables that are about 7.5 GB each!\r\n   <\/p>\r\n   <p>Code generation can effectively deliver similar speed-up benefits (and with less effort in some cases), as it's trying to\r\n      explicitly achieve the same <tt>for<\/tt> loop operations in C code that a vectorized code achieves. However, the downside for most users with the code generation\r\n      approach is that it's available with a separate product (higher cost), and only MATLAB code that supports code generation\r\n      can automatically be converted to MEX as well.\r\n   <\/p>\r\n   <h3>Customizing and Optimizing the Generated Code<a name=\"17\"><\/a><\/h3>\r\n   <p>Now with most of the basics of code generation out of the way, a few questions might be on your mind:<\/p>\r\n   <div>\r\n      <ul>\r\n         <li><b><i>\"If I want the resulting code to look different, can I just edit the generated code?\"<\/i><\/b> You can certainly edit the generated code; as you have just seen in the examples shown here, the code is very readable. However,\r\n            once you modify it, you lose the connectivity to the original MATLAB code that generated it.\r\n         <\/li>\r\n         <li><b><i>\"How can I optimize the code, or customize its look and feel?\"<\/i><\/b> One easy way to modify the generated code is to change MATLAB Coder configuration parameters. Another way to customize the\r\n            generated code is to directly edit the MATLAB code such as explicitly breaking up certain compact vector\/matrix operations\r\n            into <tt>for<\/tt> loops or other constructs you'd like to see in the generated code.\r\n         <\/li>\r\n         <li><b><i>\"What about incorporating hand-optimized or processor specific intrinsics for certain portions of the code?\"<\/i><\/b> <tt>coder.ceval<\/tt> is a command in MATLAB Coder that let's you integrate custom C code into your MATLAB code for both simulation and code generation.\r\n            Using this you can use hand-optimized or legacy C code in your algorithms. <i>Embedded Coder<\/i> is another product that adds many code optimization and customization capabilities to MATLAB Coder such as using code replacement\r\n            technology to incorporate optimized C code. It also lets you to customize the look-and-feel of the code.\r\n         <\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Learning More About MATLAB Coder<a name=\"18\"><\/a><\/h3>\r\n   <p>You can find more information about MATLAB Coder on the <a href=\"https:\/\/www.mathworks.com\/products\/matlab-coder\/\">product page<\/a>, which includes demos and recorded webinars. The <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/coder\/ug\/ug_intropage.html\">product documentation<\/a> is also an excellent resource to find answers to questions you might have when starting with this product.\r\n   <\/p>\r\n   <p>Please feel free to share your thoughts and comments on topics discussed here in this posting <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=296#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_118ae3094d7b413687ac64ea126cf023() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='118ae3094d7b413687ac64ea126cf023 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 118ae3094d7b413687ac64ea126cf023';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Arvind Ananthan';\r\n        copyright = 'Copyright 2011 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \r\n-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_118ae3094d7b413687ac64ea126cf023()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.13<br><\/p>\r\n<\/div>\r\n<!--\r\n118ae3094d7b413687ac64ea126cf023 ##### SOURCE BEGIN #####\r\n%% Generating C Code from Your MATLAB Algorithms\r\n% I am pleased to introduce guest blogger Arvind Ananthan. Arvind is the\r\n% Product Marketing Manager for\r\n% <https:\/\/www.mathworks.com\/products\/matlab-coder\/ MATLAB Coder> and\r\n% <https:\/\/www.mathworks.com\/products\/fixed\/ Fixed-Point Toolbox>. His main\r\n% focus in this post is to introduce basics of MATLAB Coder, talk about the\r\n% workflow, its use cases, and show examples of generated C code.\r\n%% A Brief History of MATLAB to C\r\n% In April, 2011, MathWorks introduced MATLAB Coder as a stand-alone\r\n% product to generate C code from MATLAB code. This tool lets user generate\r\n% readable, portable, and customizable C code from their MATLAB algorithms.\r\n% \r\n% Many astute readers will notice that C code generation from MATLAB isn't\r\n% really brand new - and that we've had this capability to generate C code\r\n% from MATLAB for quite some time now. Yes, that's true - we've been\r\n% incubating this technology for quite some time till we felt it was ready\r\n% to debut as a stand alone tool. Here's a timeline of this technology over\r\n% the past few years:\r\n% \r\n% * *2004* - Introduced the _Embedded MATLAB Function_ block in Simulink\r\n% * *2007* - Introduced the |emlc| function in Real-Time Workshop (now\r\n% called Simulink Coder) to generate stand alone C from MATLAB\r\n% * *2011* - Released MATLAB Coder, the first stand-alone product from\r\n% MathWorks to generate portable and readable C code from MATLAB code.\r\n% \r\n%% A Simple Example\r\n% Let me introduce the basics of using MATLAB Coder through a very simple\r\n% example that multiplies two variables. Let's generate C code from the\r\n% following MATLAB function that multiplies two inputs:\r\ndbtype simpleProduct.m\r\n%%\r\n%\r\n%%\r\n%\r\n% To generate C code from this function using MATLAB Coder, I first have to\r\n% specify the size and data types of my inputs - I can do this through the\r\n% MATLAB Coder UI (shown in the section below) where I specify my inputs as\r\n% a [1x5] and [5x2] single precision matrices, and subsequently generate\r\n% the following C code:\r\ndbtype simpleProduct.c\r\n%%\r\n% MATLAB is a polymorphic language which means a single function, such as\r\n% |simpleProduct|, can accept input arguments of different size and data\r\n% types and output correct results. This function can behave as a simple\r\n% scalar product, a dot product, or a matrix multiplier depending on what\r\n% inputs you pass.\r\n%\r\n% Languages like C are said to be \u00e2\u20ac\u0153stongly typed,\u00e2\u20ac\ufffd which requires you to\r\n% create a different version of a function for every variation of input\r\n% data size and types. Hence, when you write C code to implement\r\n% |simpleProduct|, you have to know ahead of time the sizes and the data\r\n% types of your inputs so you can implement the right variant.\r\n%\r\n% While MATLAB Coder helps you move from the highly flexible world of\r\n% MATLAB to a strongly typed world of C, you still have to specify all of\r\n% the constraints C expects. You do this in MATLAB Coder by creating a\r\n% MATLAB Coder project file (|simpleProduct.prj| in this case) where you\r\n% can specify the  various code generation parameters including the sizes\r\n% and data types of your inputs as shown below.\r\n% \r\n% <<simpleProductPRJ.png>>\r\n%\r\n% You can also edit the default configuration parameters by clicking on the\r\n% _'More Settings'_ link which appears on the 'Build' tab of this project\r\n% UI .\r\n%%\r\n% In the example above, I turned off a few default options such as\r\n% including comments in the generated code just so you can see how compact\r\n% the code is. You not only get the option to generate comments in the\r\n% resulting C code, but also inlcude the original MATLAB code as comments\r\n% in the corresponding sections of the generated code. This helps with\r\n% traceability of your C code to your original algorithms.\r\n%\r\n%% Detailed MATLAB Coder Worfklow\r\n%\r\n% The simple example above quickly illustrates the process of generating\r\n% code with MATLAB coder and shows how the resulting C code looks.\r\n%\r\n% Naturally, your real-world functions are going to be much more involved\r\n% and may run into hundreds or even thousands of lines of MATLAB Code. To\r\n% help you handle that level of complexity, you would need an iterative\r\n% process, like the 3-step workflow described here, that guides you through\r\n% the task of code generation incrementally:\r\n% \r\n% # *Prepare:* First, prepare your code to ensure that you can indeed\r\n% generate code from your MATLAB algorithm. The convenience of MATLAB\r\n% language doesn't map directly to the constrained behavior of C. You may\r\n% have to re-write portions of your MATLAB code so it uses the MATLAB\r\n% language features that support this mapping from MATLAB to C.\r\n% # *Test & Verify:* Next, you generate a MEX function to test that your\r\n% preparation step is correct. If the tool is successful in generating a\r\n% MEX function then you are ready to verify the results of this MEX\r\n% function against the original MATLAB code. If not, you'd have to iterate\r\n% on the previous step till you can successfully generate a MEX function.\r\n% # *Generate:* Finally, you generate C source code and further iterate\r\n% upon your MATLAB code in order to control the look and feel or the\r\n% performance of your C code.You can also generate an optimized MEX\r\n% function by turning off certain memory integrity checks and debug options\r\n% that could slow down its execution at this stage.\r\n%\r\n% I'll now demonstrate this concept using a slightly more involved example.\r\n% The following MATLAB code implements the Newton-Raphson numerical\r\n% technique for computing the n-th root of a real valued number.\r\n%\r\ndbtype newtonSearchAlgorithm.m\r\n%% \r\n% Our first step towards generating C code from this file is to prepare it\r\n% for code generation. For code generation, each variable inside your\r\n% MATLAB code must be intialized, which means specifying its size and\r\n% data type. In this case, I'll choose to initialize the variable |h| to a\r\n% static maximum size, |h = zeros(1,50)|, as it doesn't grow beyond a\r\n% length of 50 inside the |for| loop.\r\n% \r\n% You can invoke the code generation function using the GUI or the\r\n% command line (through the |codegen| command). Without worrying about the\r\n% details of this approach, let's look at the generated C code:\r\ndbtype newtonSearchAlgorithmMLC.c\r\n%%\r\n% The subfunction |fcnDerivative| is inlined in the generated C code.  You\r\n% can choose to not inline the code by putting this command\r\n% |coder.inline('never')| in the MATLAB file.\r\n%% Support for Dynamic Sizing \r\n% If you have variable in your MATLAB code that needs to vary its size\r\n% during execution, you can choose to deal with this in three different\r\n% ways in the generated C code:\r\n% \r\n% # *Static allocation with fixed maximum size:* you can initialize\r\n% variables to the maximum possible static size (like I did in the example\r\n% above). In the generated code, memory is prealloacted to this size.\r\n% # *Variable sizing with maximum size allocation:* this option will\r\n% declare the memory for the variable in the generated code to its maximum\r\n% possible size, but you can dynamically grow or shrink the variable size\r\n% within this allocated maximum.\r\n% # *Variable sizing with dynamic memory allocation:* this results in the\r\n% generated code using |malloc| to allocate the memory for the variables\r\n% that change in size during code execution.\r\n%\r\n% The last two options can be enabled by turning on the _*variable-sizing*_\r\n% feature in the configuration parameters. However, do remember that\r\n% enabling this option also makes the resulting C code bigger in size - so\r\n% if you can avoid it, you can get much more compact and possibly more\r\n% efficient code.\r\n%\r\n%% Use Cases of MATLAB Coder\r\n%\r\n% The primary use of MATLAB Coder is to enable algorithm developers and\r\n% system engineers working in MATLAB to quickly generate readable and\r\n% portable C code. The generated C code can be used in different ways\r\n% supporting different workflows. Here are a few use cases of MATLAB Coder:\r\n%\r\n% # *Create standalone executables* from your algorithms for prototyping on\r\n% a PC\r\n% # *Speed up* your MATLAB algorithm code (or portions of it) by generating\r\n% and executing the MEX functions\r\n% # *Integrate* your MATLAB algorithms as C source code or compiled library\r\n% with your hand-written software\r\n%\r\n% I won't be talking about creating standalone executables or creating\r\n% libraries from MATLAB Coder in this blog; I'll, however, say a few words\r\n% on generating MEX functions.\r\n%\r\n%% Generating MEX Functions for Simulation Acceleration\r\n% The MEX interface enables you to integrate C code into MATLAB. One common\r\n% use of MEX is to speed up performance bottlenecks in MATLAB code by\r\n% re-writing them in C and executing them back in MATLAB as MEX functions.\r\n% MATLAB Coder can save you time and effort by automatically generating MEX\r\n% functions from your MATLAB code (and allowing you to import legacy C code\r\n% easily as well).\r\n% \r\n% The speed-up you get through automatic MEX generation can vary quite a\r\n% bit depending on the application. In some cases, you may not get any\r\n% speed up at all, or possibly even a slow-down, as MATLAB language has\r\n% gotten quite smart and efficient in computing many built-in functions by\r\n% automatically taking advantage of processor specific routines (such as\r\n% Intel Performance Primitives) and multithreading to utilize multiple\r\n% cores.\r\n% \r\n% A few guidelines that you can use to determine if your algorithm is a\r\n% good candidate for speed-up with MEX are:\r\n%\r\n% * your algorithm contains multiply nested |for| loops, and possibly\r\n% handles state calculations (making each iteration\r\n% dependent on the previous one)\r\n% * your MATLAB code is hard\/impossible to vectorize\r\n% * most of the processing cycles in your algorithm are *not* spent on\r\n% already optimized built-in functions such as |fft| or |inv|, etc.\r\n% * you don't rely heavily on toolbox functions (especially those\r\n% unsupported for code generation) in your algorithms\r\n%\r\n% In these cases, you can expect to see a speed-up. Let's look at a\r\n% realistic example that illustrates this concept.\r\n%\r\n% The example I chose here is one that my colleague\r\n% <https:\/\/blogs.mathworks.com\/loren\/2008\/06\/25\/speeding-up-matlab-applications\/\r\n% Sarah Zaranek> had highlighted in her guest blog on vectorization.\r\n%\r\n%%\r\n% I modified the original MATLAB script from that article into a function\r\n% as only functions are supported by MATLAB Coder. The other change that I\r\n% made to the original script was to initialize the output variables |subs|\r\n% and |vals| (as all variables in your code has to be defined\/intialized\r\n% once when used with MATLAB Coder). And by turning on the variable sizing\r\n% feature (using dynamic memory allocation), I didn't have to preallocate\r\n% it to a sufficiently large enough size to accomodate its growth, which\r\n% would use more memory (often a lot) than needed.\r\n% \r\n% The following statements create and use a MATLAB Coder configuration\r\n% object with support for variable size arrays and dynamic memory\r\n% allocation to generate a MEX function.\r\n\r\n% Create a MEX configuration object\r\ncfg = coder.config('mex');  \r\n% Turn on dynamic memory allocation\r\ncfg.DynamicMemoryAllocation = 'AllVariableSizeArrays'; \r\n% Generate MEX function\r\ncodegen -config cfg gridSpeedUpFcn -args {10}  \r\ndisp('MEX generation complete!')\r\n%%\r\n% This generates a MEX function in the current folder. I'll use\r\n% |tic|, and |toc| to estimate the execution times of the original MATLAB\r\n% function and its MEX version.\r\n%\r\n% I run each function multiple times inside a |for| loop and use only\r\n% the last few runs for our computation time calculation so we can minimize\r\n% the effects of initialization and caching.\r\n\r\nMToc = zeros(1,30);\r\nMexToc = zeros(1,30);\r\nfor j = 1:30\r\n    tic; gridSpeedUpFcn(10); \r\n    MToc(j) = toc; \r\nend\r\n\r\nfor j = 1:30\r\n    tic; gridSpeedUpFcn_mex(10); \r\n    MexToc(j) = toc; \r\nend\r\n\r\neff_M_time = mean(MToc(1,21:30));\r\neff_Mex_time = mean(MexToc(1,21:30));\r\n\r\ndisp(['MATLAB code execution time (with nx=10): ', num2str(eff_M_time)])\r\ndisp(['MEX code executing time (with nx=10): ', num2str(eff_Mex_time)])\r\n\r\ndisp([' Speed up factor: ', num2str(eff_M_time\/eff_Mex_time)]);\r\n\r\n%%\r\n% The speed up we see in this example is more pronounced for larger values\r\n% of |nx| (and would vary between different computers).\r\n\r\n%% Vectorization and Code Generation\r\n% Sarah, in her blog\r\n% <https:\/\/blogs.mathworks.com\/loren\/2008\/06\/25\/speeding-up-matlab-applications\/\r\n% article>, explains quite nicely on how to vectorize this code using\r\n% |meshgrid| and |ndgrid| to explode the variables in support of\r\n% vectorization, and get similar levels of speed up.\r\n%\r\n% Sarah paid a small price in code readability for her vectorization\r\n% efforts, but a much larger price in memory consumption. This points to a\r\n% common trade-off when vectorizing MATLAB code: execution time vs. memory\r\n% consumption. The temporary variables which enable us to remove loops\r\n% through matrix math are often very large, effectively limiting the number\r\n% of iterations you can take before running out of memory. For instance, if\r\n% we run her algorithm for a 1,000x1,000 grid instead of a 100x100 grid, we\r\n% would create 9 double precision variables that are about 7.5 GB each!\r\n%\r\n% Code generation can effectively deliver similar speed-up benefits\r\n% (and with less effort in some cases), as it's trying to explicitly\r\n% achieve the same |for| loop operations in C code that a vectorized code\r\n% achieves. However, the downside for most users with the code generation\r\n% approach is that it's available with a separate product (higher cost),\r\n% and only MATLAB code that supports code generation can automatically be\r\n% converted to MEX as well.\r\n%% Customizing and Optimizing the Generated Code\r\n% Now with most of the basics of code generation out of the way, a few\r\n% questions might be on your mind:\r\n% \r\n% * *_\"If I want the resulting code to look different, can I just edit the\r\n% generated code?\"_* You can certainly edit the generated code; as you have\r\n% just seen in the examples shown here, the code is very readable. However,\r\n% once you modify it, you lose the connectivity to the original MATLAB code\r\n% that generated it.\r\n% * *_\"How can I optimize the code, or customize its look and feel?\"_* One\r\n% easy way to modify the generated code is to change MATLAB Coder\r\n% configuration parameters. Another way to customize the generated code is\r\n% to directly edit the MATLAB code such as explicitly breaking up certain\r\n% compact vector\/matrix operations into |for| loops or other constructs\r\n% you'd like to see in the generated code.\r\n% * *_\"What about incorporating hand-optimized or processor specific\r\n% intrinsics for certain portions of the code?\"_* |coder.ceval| is a\r\n% command in MATLAB Coder that let's you integrate custom C code into your\r\n% MATLAB code for both simulation and code generation. Using this you can\r\n% use hand-optimized or legacy C code in your algorithms. _Embedded Coder_\r\n% is another product that adds many code optimization and customization\r\n% capabilities to MATLAB Coder such as using code replacement technology to\r\n% incorporate optimized C code. It also lets you to customize the\r\n% look-and-feel of the code.\r\n%% Learning More About MATLAB Coder\r\n% You can find more information about MATLAB Coder on the\r\n% <www-external-test.mathworks.com\/products\/matlab-coder\/ product page>,\r\n% which includes demos and recorded webinars. The\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/toolbox\/coder\/ug\/ug_intropage.html product\r\n% documentation> is also an excellent resource to find answers to questions\r\n% you might have when starting with this product.\r\n%\r\n% Please feel free to share your thoughts and comments on topics discussed\r\n% here in this posting <https:\/\/blogs.mathworks.com\/loren\/?p=296#respond\r\n% here>.\r\n\r\n##### SOURCE END ##### 118ae3094d7b413687ac64ea126cf023\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      I am pleased to introduce guest blogger Arvind Ananthan. Arvind is the Product Marketing Manager for MATLAB Coder and Fixed-Point Toolbox. His main focus in this post is to introduce... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2011\/11\/14\/generating-c-code-from-your-matlab-algorithms\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[46,24],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/296"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=296"}],"version-history":[{"count":4,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/296\/revisions"}],"predecessor-version":[{"id":1950,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/296\/revisions\/1950"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=296"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=296"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=296"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}