{"id":60,"date":"2006-10-25T15:43:25","date_gmt":"2006-10-25T20:43:25","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=60"},"modified":"2006-10-31T13:30:47","modified_gmt":"2006-10-31T18:30:47","slug":"cute-tricks-in-matlab-adapted-from-other-languages","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2006\/10\/25\/cute-tricks-in-matlab-adapted-from-other-languages\/","title":{"rendered":"Cute Tricks in MATLAB Adapted from Other Languages"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>I recently saw <a href=\"http:\/\/www.sjbaker.org\/steve\/software\/cute_code.html\">Steve Baker's web site<\/a> while searching for something.  It contains some cute (Steve's word) programming tricks and I thought I would show how to\r\n         do a couple of these in MATLAB.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Power of Two Test<\/a><\/li>\r\n         <li><a href=\"#3\">Swap Two Integer Values<\/a><\/li>\r\n         <li><a href=\"#5\">Force All Non-zeros to 1<\/a><\/li>\r\n         <li><a href=\"#7\">What Byte Order is My Computer?<\/a><\/li>\r\n         <li><a href=\"#10\">Set Different Bits<\/a><\/li>\r\n         <li><a href=\"#11\">Other Tricks?<\/a><\/li>\r\n         <li><a href=\"#12\">Acknowledgment<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Power of Two Test<a name=\"1\"><\/a><\/h3>\r\n   <p>Here's the C code:<\/p><pre>     b = ((n&amp;(n-1))==0) ;<\/pre><p>and now the M code:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">n = 1:8\r\nispow2 = bitand(n,n-1) == 0<\/pre><pre style=\"font-style:oblique\">n =\r\n     1     2     3     4     5     6     7     8\r\nispow2 =\r\n     1     1     0     1     0     0     0     1\r\n<\/pre><h3>Swap Two Integer Values<a name=\"3\"><\/a><\/h3>\r\n   <p>C code to swap integers x and y  <tt>x = x ^ y ;<\/tt>  <tt>y = x ^ y ;<\/tt>  <tt>x = x ^ y ;<\/tt><\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">x = 3\r\ny = 17\r\nx = bitxor(x,y)\r\ny = bitxor(x,y)\r\nx = bitxor(x,y)<\/pre><pre style=\"font-style:oblique\">x =\r\n     3\r\ny =\r\n    17\r\nx =\r\n    18\r\ny =\r\n     3\r\nx =\r\n    17\r\n<\/pre><p>Of course, I showed how to do this more easily a while ago using an anonymous function:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">swap=@(varargin)varargin{nargin:-1:1};\r\nx = 3\r\ny = 17\r\n[x,y] = swap(x,y)<\/pre><pre style=\"font-style:oblique\">x =\r\n     3\r\ny =\r\n    17\r\nx =\r\n    17\r\ny =\r\n     3\r\n<\/pre><h3>Force All Non-zeros to 1<a name=\"5\"><\/a><\/h3>\r\n   <p>The C code:<\/p><pre>              b = !!a ;<\/pre><p>and the MATLAB code:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">a = [0 1 3 0 5 7 9 0 -3 0 0]\r\nb = +(a~=0)  <span style=\"color: #228B22\">% use leading + to make result double instead of logical.<\/span><\/pre><pre style=\"font-style:oblique\">a =\r\n     0     1     3     0     5     7     9     0    -3     0     0\r\nb =\r\n     0     1     1     0     1     1     1     0     1     0     0\r\n<\/pre><h3>What Byte Order is My Computer?<a name=\"7\"><\/a><\/h3>\r\n   <p>The C code:<\/p><pre>     int i = 1 ;\r\n     little_endian = *((char *) &amp;i ) ;<\/pre><p>and the MATLAB code:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">a = uint16(1);\r\nb = typecast(a,<span style=\"color: #A020F0\">'uint8'<\/span>)\r\nlittle = [1 0];  <span style=\"color: #228B22\">% big = [0 1];<\/span>\r\nislittle = isequal(b,little)<\/pre><pre style=\"font-style:oblique\">b =\r\n    1    0\r\nislittle =\r\n     1\r\n<\/pre><p>or<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">[omit, omit, endian] = computer<\/pre><pre style=\"font-style:oblique\">omit =\r\n  2.1475e+009\r\nomit =\r\n  2.1475e+009\r\nendian =\r\nL\r\n<\/pre><h3>Set Different Bits<a name=\"10\"><\/a><\/h3>\r\n   <p>Set the least significant bit to 0.  Here's the C code.<\/p><pre>    n&amp;(n-1)<\/pre><p>and the M code:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">n = uint8(0:7)\r\nlb1 = bitset(n,1,0)<\/pre><pre style=\"font-style:oblique\">n =\r\n    0    1    2    3    4    5    6    7\r\nlb1 =\r\n    0    0    2    2    4    4    6    6\r\n<\/pre><h3>Other Tricks?<a name=\"11\"><\/a><\/h3>\r\n   <p>Share <a href=\"?p=60#respond\">your MATLAB tricks<\/a> with me.\r\n   <\/p>\r\n   <h3>Acknowledgment<a name=\"12\"><\/a><\/h3>\r\n   <p>Steve Eddins, famous for many things, including his blog on image processing, just updated one of our blog publishing tools,\r\n      allowing you to see the code behind most of our posts with the push of a mouse button. Pretty cool, huh!  Be sure to read\r\n      his recent blog article about the <a href=\"https:\/\/blogs.mathworks.com\/steve\/?p=87\">default MATLAB image<\/a>.\r\n   <\/p><script language=\"JavaScript\"> \r\n    function grabCode_418ab069b2ed4a2c87ebb132016aa9a8() {\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='418ab069b2ed4a2c87ebb132016aa9a8 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 418ab069b2ed4a2c87ebb132016aa9a8';\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 = 'Loren Shure';\r\n        copyright = 'Copyright 2006 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      <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_418ab069b2ed4a2c87ebb132016aa9a8()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code<\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.3<br><\/p>\r\n<\/div>\r\n<!--\r\n418ab069b2ed4a2c87ebb132016aa9a8 ##### SOURCE BEGIN #####\r\n%% Cute Tricks in MATLAB Adapted from Other Languages\r\n% I recently saw <http:\/\/www.sjbaker.org\/steve\/software\/cute_code.html Steve Baker's web site>\r\n% while searching for something.  It contains some cute (Steve's word)\r\n% programming tricks and I thought I would show how to do a couple of these\r\n% in MATLAB.\r\n%% Power of Two Test\r\n% Here's the C code: \r\n%\r\n%       b = ((n&(n-1))==0) ;\r\n%%\r\n% and now the M code:\r\nn = 1:8\r\nispow2 = bitand(n,n-1) == 0\r\n\r\n\r\n%% Swap Two Integer Values\r\n% C code to swap integers x and y\r\n%  |x = x ^ y ;|\r\n%  |y = x ^ y ;|\r\n%  |x = x ^ y ;|\r\n\r\nx = 3\r\ny = 17\r\nx = bitxor(x,y)\r\ny = bitxor(x,y)\r\nx = bitxor(x,y)\r\n%%\r\n% Of course, I showed how to do this more easily a while ago using an\r\n% anonymous function:\r\nswap=@(varargin)varargin{nargin:-1:1};\r\nx = 3\r\ny = 17\r\n[x,y] = swap(x,y)\r\n\r\n%% Force All Non-zeros to 1\r\n% The C code:\r\n%\r\n%                b = !!a ;\r\n%%\r\n% and the MATLAB code:\r\na = [0 1 3 0 5 7 9 0 -3 0 0]\r\nb = +(a~=0)  % use leading + to make result double instead of logical.\r\n\r\n%% What Byte Order is My Computer?\r\n% The C code:\r\n%\r\n%       int i = 1 ;\r\n%       little_endian = *((char *) &i ) ;\r\n%%\r\n% and the MATLAB code:\r\na = uint16(1);\r\nb = typecast(a,'uint8')\r\nlittle = [1 0];  % big = [0 1];\r\nislittle = isequal(b,little)\r\n\r\n%%\r\n% or\r\n[omit, omit, endian] = computer\r\n\r\n%% Set Different Bits\r\n% Set the least significant bit to 0.  Here's the C code.\r\n%\r\n%      n&(n-1)\r\n%\r\n% and the M code:\r\nn = uint8(0:7)\r\nlb1 = bitset(n,1,0)\r\n%% Other Tricks?\r\n% Share <?p=60#respond your MATLAB tricks> with me.\r\n%% Acknowledgment\r\n% Steve Eddins, famous for many things, including his blog on image\r\n% processing, just updated one of our blog publishing tools, allowing you\r\n% to see the code behind most of our posts with the push of a mouse button.\r\n% Pretty cool, huh!  Be sure to read his recent blog article about the\r\n% <https:\/\/blogs.mathworks.com\/steve\/?p=87 default MATLAB image>.\r\n\r\n\r\n##### SOURCE END ##### 418ab069b2ed4a2c87ebb132016aa9a8\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      I recently saw Steve Baker's web site while searching for something.  It contains some cute (Steve's word) programming tricks and I thought I would show how to\r\n         do a couple of... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/10\/25\/cute-tricks-in-matlab-adapted-from-other-languages\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[15],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/60"}],"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=60"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/60\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=60"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=60"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=60"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}