{"id":5429,"date":"2014-07-11T08:58:40","date_gmt":"2014-07-11T12:58:40","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/?p=5429"},"modified":"2014-07-11T08:58:40","modified_gmt":"2014-07-11T12:58:40","slug":"c-mex-programming-tutorial-examples","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2014\/07\/11\/c-mex-programming-tutorial-examples\/","title":{"rendered":"C-MEX Programming Tutorial Examples"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/answers\/contributors\/3208495\">Sean<\/a>'s pick this week is <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/44163-c-mex-programming-tutorial-examples\">\"C-MEX Programming Tutorial Examples\"<\/a> by <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/128396\">Ilias Konsoulas<\/a>.\r\n      <\/p>\r\n   <\/introduction>\r\n   <div>\r\n   <\/div>\r\n   <p>I spent the last few days at the 2014 SIAM conference in Chicago manning the MathWorks booth with a few of our developers.\r\n       We were asked many questions about the products, new features, life at MathWorks, and of course for t-shirts and rubik's\r\n      cubes.\r\n   <\/p>\r\n   <p>One of the questions I was asked was along the lines of: \"How do I get started with MEX?\". <a href=\"\">MEX<\/a>, which is short for \"MATLAB Executable\", is compiled C\/C++ or Fortran code with the appropriate MATLAB wrappers on it so\r\n      that it can be called at the command line like any other MATLAB function.  Personally, I haven't written any productive C\/C++\r\n      code since high school about ten years ago. When I need C or C++ code, I develop the algorithm in MATLAB and then use <a href=\"https:\/\/www.mathworks.com\/products\/matlab-coder\/\">MATLAB Coder<\/a> to automagically generate equivalent C code.\r\n   <\/p>\r\n   <p>I had found Ilias' submission a while ago and added it to the \"to experiment with list\".  Now, it allowed me to answer this\r\n      question while sounding knowledgable and getting the user started on his journey.\r\n   <\/p>\r\n   <p>The submission comes with nine heavily commented C files that do simple matrix manipulations like summing and reshaping as\r\n      well as a readme file that documents the package.  The C files show the MEX syntax, required headers and some good programming\r\n      practices like error checking.\r\n   <\/p>\r\n   <p>Curious if I could actually write my own hand-written MEX file, I challenged myself to write one which calculates the sum\r\n      of the diagonal of a matrix.  I started by editing Ilias' <tt>transposeM.c<\/tt> which should be a good blueprint.\r\n   <\/p>\r\n   <p>After some time, having it fail to compile 20ish times, and getting stuck in an infinite loop only once(!), (I forgot to increment\r\n      <i>i<\/i> in the <tt>for<\/tt>-loop), it works!\r\n   <\/p>\r\n   <p>Here's a snapshot of the file:<\/p>\r\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/Sean\/mainmexex\/traceM.PNG\"> <\/p>\r\n   <p>That was an exercise in frustration.  How about we just use MATLAB Coder to do this?  First, I wrote a MATLAB function to\r\n      calculate the sum of the diagonal; there happens to be a function called <tt>trace<\/tt> that does this:\r\n   <\/p>\r\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/Sean\/mainmexex\/mytrace.PNG\"> <\/p>\r\n   <p>Now to generate C code, you can use the MATLAB Coder App to generate code interactively, or do it programatically with <a href=\"\"><tt>codegen<\/tt><\/a>.  I'll take the latter approach since it's easier to automate.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #228B22\">% Input must be a double precision matrix of size \"up-to-inf\" by \"up-to-inf\"<\/span>\r\ninput_specs = coder.typeof(zeros,inf,inf);\r\ncodegen <span style=\"color: #A020F0\">mytrace<\/span> <span style=\"color: #A020F0\">-args<\/span> <span style=\"color: #A020F0\">{input_specs}<\/span><\/pre><p>This generates <tt>mytrace_mex<\/tt> which I can call like any other function.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">rng(5) <span style=\"color: #228B22\">% reproducible<\/span>\r\nX = gallery(<span style=\"color: #A020F0\">'randhess'<\/span>,7); <span style=\"color: #228B22\">% a matrix<\/span>\r\nt = mytrace_mex(X); <span style=\"color: #228B22\">% use mex file<\/span>\r\ndisp(t)<\/pre><pre style=\"font-style:oblique\">   -0.1573\r\n<\/pre><p>Now let's see if the two C implementations and the MATLAB implementation agree using the <a href=\"\">MATLAB unit testing framework<\/a>.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #228B22\">% Build interactive test object<\/span>\r\nTester = matlab.unittest.TestCase.forInteractiveUse;\r\n\r\n<span style=\"color: #228B22\">% Assert equality<\/span>\r\nassertEqual(Tester,trace(X),traceM(X)) <span style=\"color: #228B22\">% My C implementation<\/span>\r\nassertEqual(Tester,trace(X),mytrace_mex(X)) <span style=\"color: #228B22\">% MATLAB Coder's implementation<\/span><\/pre><pre style=\"font-style:oblique\">Interactive assertion passed.\r\nInteractive assertion passed.\r\n<\/pre><h3>Comments<a name=\"5\"><\/a><\/h3>\r\n   <p>Give it a try and let us know what you think <a href=\"https:\/\/blogs.mathworks.com\/pick\/?p=5429#respond\">here<\/a> or leave a <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/44163-c-mex-programming-tutorial-examples#comments\">comment<\/a> for Ilias.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_4e17aca888e04d008e13227934d43482() {\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='4e17aca888e04d008e13227934d43482 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 4e17aca888e04d008e13227934d43482';\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 = 'Sean de Wolski';\r\n        copyright = 'Copyright 2014 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_4e17aca888e04d008e13227934d43482()\"><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; R2014a<br><\/p>\r\n<\/div>\r\n<!--\r\n4e17aca888e04d008e13227934d43482 ##### SOURCE BEGIN #####\r\n%% C-MEX Programming Tutorial Examples\r\n%\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/answers\/contributors\/3208495 Sean>'s pick this week is\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/44163-c-mex-programming-tutorial-examples \"C-MEX Programming Tutorial Examples\"> by\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/128396 Ilias Konsoulas>.\r\n% \r\n\r\n%% \r\n% I spent the last few days at the 2014 SIAM conference in Chicago manning\r\n% the MathWorks booth with a few of our developers.  We were asked many\r\n% questions about the products, new features, life at MathWorks, and of\r\n% course for t-shirts and rubik's cubes.\r\n% \r\n% One of the questions I was asked was along the lines of: \"How do I get\r\n% started with MEX?\".\r\n% < MEX>,\r\n% which is short for \"MATLAB Executable\", is compiled C\/C++ or Fortran code\r\n% with the appropriate MATLAB wrappers on it so that it can be called at\r\n% the command line like any other MATLAB function.  Personally, I haven't\r\n% written any productive C\/C++ code since high school about ten years ago.\r\n% When I need C or C++ code, I develop the algorithm in MATLAB and then use\r\n% <https:\/\/www.mathworks.com\/products\/matlab-coder\/ MATLAB Coder> to\r\n% automagically generate equivalent C code.\r\n%\r\n% I had found Ilias' submission a while ago and added it to the \"to\r\n% experiment with list\".  Now, it allowed me to answer this question while\r\n% sounding knowledgable and getting the user started on his journey.\r\n%\r\n% The submission comes with nine heavily commented C files that do simple\r\n% matrix manipulations like summing and reshaping as well as a readme file\r\n% that documents the package.  The C files show the MEX syntax, required\r\n% headers and some good programming practices like error checking.\r\n%\r\n% Curious if I could actually write my own hand-written MEX file, I\r\n% challenged myself to write one which calculates the sum of the diagonal\r\n% of a matrix.  I started by editing Ilias' |transposeM.c| which should be\r\n% a good blueprint.\r\n%\r\n% After some time, having it fail to compile 20ish times, and getting stuck\r\n% in an infinite loop only once(!), (I forgot to increment _i_ in the\r\n% |for|-loop), it works!\r\n%\r\n% Here's a snapshot of the file:\r\n%\r\n% <<traceM.PNG>>\r\n\r\n\r\n%%\r\n% That was an exercise in frustration.  How about we just use MATLAB Coder\r\n% to do this?  First, I wrote a MATLAB function to calculate the sum of\r\n% the diagonal; there happens to be a function called |trace| that does\r\n% this:\r\n% \r\n% <<mytrace.PNG>>\r\n%\r\n% Now to generate C code, you can use the MATLAB Coder App to generate code\r\n% interactively, or do it programatically with\r\n% <\r\n% |codegen|>.  I'll take the latter approach since it's easier to automate.\r\n\r\n% Input must be a double precision matrix of size \"up-to-inf\" by \"up-to-inf\"\r\ninput_specs = coder.typeof(zeros,inf,inf);\r\ncodegen mytrace -args {input_specs}\r\n\r\n%%\r\n% This generates |mytrace_mex| which I can call like any other function.\r\n%\r\n\r\nrng(5) % reproducible\r\nX = gallery('randhess',7); % a matrix\r\nt = mytrace_mex(X); % use mex file\r\ndisp(t)\r\n\r\n%%\r\n% Now let's see if the two C implementations and the MATLAB implementation\r\n% agree.\r\n\r\n% Build interactive test object\r\nTester = matlab.unittest.TestCase.forInteractiveUse;\r\n\r\n% Assert equality\r\nassertEqual(Tester,trace(X),traceM(X)) % My C implementation\r\nassertEqual(Tester,trace(X),mytrace_mex(X)) % MATLAB Coder's implementation\r\n\r\n%% Comments\r\n% \r\n% Give it a try and let us know what you think\r\n% <https:\/\/blogs.mathworks.com\/pick\/?p=5429#respond here> or leave a\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/44163-c-mex-programming-tutorial-examples#comments\r\n% comment> for Ilias.\r\n%\r\n \r\n\r\n##### SOURCE END ##### 4e17aca888e04d008e13227934d43482\r\n-->","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/Sean\/mainmexex\/traceM.PNG\" onError=\"this.style.display ='none';\" \/><\/div><p>\r\n   \r\n      Sean's pick this week is \"C-MEX Programming Tutorial Examples\" by Ilias Konsoulas.\r\n      \r\n   \r\n   \r\n   \r\n   I spent the last few days at the 2014 SIAM conference... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2014\/07\/11\/c-mex-programming-tutorial-examples\/\">read more >><\/a><\/p>","protected":false},"author":87,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/5429"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/users\/87"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/comments?post=5429"}],"version-history":[{"count":8,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/5429\/revisions"}],"predecessor-version":[{"id":5438,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/5429\/revisions\/5438"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=5429"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=5429"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=5429"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}