{"id":281,"date":"2011-07-07T17:48:00","date_gmt":"2011-07-07T17:48:00","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2011\/07\/07\/simpler-control-of-random-number-generation-in-matlab\/"},"modified":"2016-08-02T12:51:03","modified_gmt":"2016-08-02T17:51:03","slug":"simpler-control-of-random-number-generation-in-matlab","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2011\/07\/07\/simpler-control-of-random-number-generation-in-matlab\/","title":{"rendered":"Simpler Control of Random Number Generation in MATLAB"},"content":{"rendered":"<div class=\"content\">\n<p>Once again we're going to hear from guest blogger Peter Perkins, who is a statistical software developer here at The MathWorks.<\/p>\n<p>MATLAB has had random numbers since the beginning. But not surprisingly, as the state of that art advanced, the original<br \/>\ntools in MATLAB were not really suitable to incorporate new ideas like parallel random number generation. So R2008b saw the<br \/>\naddition of the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/ref\/randstream.html\"><tt>RandStream<\/tt><\/a> class, which was designed to support those new ideas, including new generator algorithms, multiple random number streams,<br \/>\nsubstreams, and parallel generation.<\/p>\n<p><tt>RandStream<\/tt> also fixed an old <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/math\/bsn94u0-1.html\">problem<\/a> that most people didn't even know existed, where MATLAB code that reseeded or read\/wrote the state of MATLAB's random number<br \/>\ngenerator using the pre-R2008b \"control\" syntaxes, such as<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid #c8c8c8;\">rand(<span style=\"color: #a020f0;\">'seed'<\/span>,0); <span style=\"color: #228b22;\">% may not do what you think!<\/span><\/pre>\n<p>didn't always have the effect you might have expected.<\/p>\n<p>So the introduction of <tt>RandStream<\/tt> was a good thing, providing powerful new ways of using random numbers. The problem was, with power came a price: using <tt>RandStream<\/tt> resulted in more verbose and harder-to-understand MATLAB code, required at least some knowledge of MATLAB objects, and just<br \/>\nplain <i>felt different<\/i> than the old ways of doing things.<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid #c8c8c8;\">stream = RandStream(<span style=\"color: #a020f0;\">'mt19937ar'<\/span>,<span style=\"color: #a020f0;\">'Seed'<\/span>,5489); <span style=\"color: #228b22;\">% MATLAB's start-up settings<\/span>\r\nRandStream.setGlobalStream(stream);<\/pre>\n<p>Lots of people, justifiably, gave us feedback more or less saying, \"Hey! I just want to generate random numbers! It shouldn't<br \/>\nbe like learning brain surgery!\" We listened, and in R2011a, added a new function, <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/ref\/rng.html\"><tt>rng<\/tt><\/a>, that allows you to simply, quickly, and intuitively control how MATLAB generates random numbers. <tt>rng<\/tt> is actually built on top of <tt>RandStream<\/tt>, so in that sense it isn't anything new. But it provides a simpler interface for the most common operations.<\/p>\n<p>For example, to reinitialize MATLAB's random number generator to its default settings, you use this command<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid #c8c8c8;\">rng <span style=\"color: #a020f0;\">default<\/span><\/pre>\n<p>and to reinitialize it with the seed <tt>54321<\/tt>, you use this<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid #c8c8c8;\">rng(54321);<\/pre>\n<p>You can also reseed it \"unpredictably\" using<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid #c8c8c8;\">rng <span style=\"color: #a020f0;\">shuffle<\/span><\/pre>\n<p>Definitely a simpler syntax, and yet there's still some potentially tricky ideas going on there, ideas that can trip you up.<br \/>\nA couple of years ago, I wrote <a href=\"https:\/\/blogs.mathworks.com\/loren\/2008\/11\/05\/new-ways-with-random-numbers-part-i\/\">two posts<\/a> describing the basic ideas behind random number generator seeds and states, and showed how to \"control\" the generator in<br \/>\nMATLAB, and more importantly, discussed when and <i>when not<\/i> to. All of that is still relevant and important to understand. But those posts explain it terms of <tt>RandStream<\/tt>.<\/p>\n<p>This time around, I'll just point to the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/math\/example-demos-rngdemo.html\">MATLAB User Guide section<\/a> that covers much of the same ground, but this time in terms of the <tt>rng<\/tt> function. It is a quick read, and I really recommend it to anyone who wants to understand how to use random numbers in MATLAB.<br \/>\nThe short summary is that quite often, <i>you don't need to do anything special at all<\/i> beyond just calling <tt>rand<\/tt>, <tt>randi<\/tt>, or <tt>randn<\/tt> to create random arrays. But if you need simple repeatability or independence, <tt>rng<\/tt> gets you that easily.<\/p>\n<p><tt>rng<\/tt> is also a more direct replacement than <tt>RandStream<\/tt> for the old, pre-R2008b ways of reseeding or reading\/writing the generator state. If you have code that uses those old commands,<br \/>\nyou've probably noticed that the Code Analyzer in the MATLAB editor flags them. In R2011a, the warning directs you to a <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/math\/bsn94u0-1.html\">section of the doc<\/a> that shows how to replace the old with the new.<\/p>\n<p><tt>RandStream<\/tt> is still the tool to use for more complicated situations involving multiple parallel random streams, so <tt>rng<\/tt> doesn't entirely replace it. But for most people, most of the time, <tt>rng<\/tt> is a much simpler choice.<\/p>\n<p><script>\/\/ <![CDATA[\nfunction grabCode_5cc749b562984955a5131603dd8b8dc7() {\n        \/\/ Remember the title so we can use it in the new page\n        title = document.title;\n\n        \/\/ Break up these strings so that their presence\n        \/\/ in the Javascript doesn't mess up the search for\n        \/\/ the MATLAB code.\n        t1='5cc749b562984955a5131603dd8b8dc7 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 5cc749b562984955a5131603dd8b8dc7';\n    \n        b=document.getElementsByTagName('body')[0];\n        i1=b.innerHTML.indexOf(t1)+t1.length;\n        i2=b.innerHTML.indexOf(t2);\n \n        code_string = b.innerHTML.substring(i1, i2);\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\n\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \n        \/\/ in the XML parser.\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\n        \/\/ doesn't go ahead and substitute the less-than character. \n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\n\n        author = 'Peter Perkins';\n        copyright = 'Copyright 2011 The MathWorks, Inc.';\n\n        w = window.open();\n        d = w.document;\n        d.write('\n\n\n\n\n\n<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\n\n\n\n\n\n\\n');\n      \n      d.title = title + ' (MATLAB code)';\n      d.close();\n      }\n\/\/ ]]><\/script><\/p>\n<p style=\"text-align: right; font-size: xx-small; font-weight: lighter; font-style: italic; color: gray;\"><a><span style=\"font-size: x-small; font-style: italic;\">Get<br \/>\nthe MATLAB code<br \/>\n<noscript>(requires JavaScript)<\/noscript><\/span><\/a><\/p>\n<p>Published with MATLAB\u00ae 7.12<\/p>\n<\/div>\n<p><!--\n5cc749b562984955a5131603dd8b8dc7 ##### SOURCE BEGIN #####\n%% Simpler Control of Random Number Generation in MATLAB\n% Once again we're going to hear from guest blogger\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/loadAuthor.do?objectId=1093801&objectType=author Peter Perkins>,\n% who is a statistical software developer here at The MathWorks.\n%\n% MATLAB has had random numbers since the beginning.  But not surprisingly,\n% as the state of that art advanced, the original tools in MATLAB were not\n% really suitable to incorporate new ideas like parallel random number\n% generation. So R2008b saw the addition of the\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/ref\/randstream.html % |RandStream|> class, which was designed to support those new ideas,\n% including new generator algorithms, multiple random number streams,\n% substreams, and parallel generation.\n%\n% |RandStream| also fixed an old\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/math\/bsn94u0-1.html problem> that\n% most people didn't even know existed, where MATLAB code that reseeded or\n% read\/wrote the state of MATLAB's random number generator using the\n% pre-R2008b \"control\" syntaxes, such as\nrand('seed',0); % may not do what you think!\n%%\n% didn't always have the effect you might have expected.\n%\n% So the introduction of |RandStream| was a good thing, providing powerful\n% new ways of using random numbers.  The problem was, with power came a\n% price: using |RandStream| resulted in more verbose and\n% harder-to-understand MATLAB code, required at least some knowledge of\n% MATLAB objects, and just plain _felt different_ than the old ways of\n% doing things.\nstream = RandStream('mt19937ar','Seed',5489); % MATLAB's start-up settings\nRandStream.setGlobalStream(stream);\n%%\n% Lots of people, justifiably, gave us feedback more or less saying, \"Hey!\n% I just want to generate random numbers! It shouldn't be like learning\n% brain surgery!\"  We listened, and in R2011a, added a new function,\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/ref\/rng.html |rng|>, that allows\n% you to simply, quickly, and intuitively control how MATLAB generates\n% random numbers.  |rng| is actually built on top of |RandStream|, so in\n% that sense it isn't anything new.  But it provides a simpler interface\n% for the most common operations.\n%\n% For example, to reinitialize MATLAB's random number generator to its\n% default settings, you use this command\nrng default\n%%\n% and to reinitialize it with the seed |54321|, you use this\nrng(54321);\n%%\n% You can also reseed it \"unpredictably\" using\nrng shuffle\n\n%%\n% Definitely a simpler syntax, and yet there's still some potentially\n% tricky ideas going on there, ideas that can trip you up.  A couple of\n% years ago, I wrote\n% <https:\/\/blogs.mathworks.com\/loren\/2008\/11\/05\/new-ways-with-random-numbers-part-i\/ % two posts> describing the basic ideas behind random number generator\n% seeds and states, and showed how to \"control\" the generator in MATLAB,\n% and more importantly, discussed when and _when not_ to.  All of that is\n% still relevant and important to understand.  But those posts explain it\n% terms of |RandStream|.\n%\n% This time around, I'll just point to the\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/math\/example-demos-rngdemo.html % MATLAB User Guide section> that covers much of the same ground, but this\n% time in terms of the |rng| function. It is a quick read, and I really\n% recommend it to anyone who wants to understand how to use random numbers\n% in MATLAB.  The short summary is that quite often, _you don't need to do\n% anything special at all_ beyond just calling |rand|, |randi|, or |randn|\n% to create random arrays.  But if you need simple repeatability or\n% independence, |rng| gets you that easily.\n%\n% |rng| is also a more direct replacement than |RandStream| for the old,\n% pre-R2008b ways of reseeding or reading\/writing the generator state.  If\n% you have code that uses those old commands, you've probably noticed that\n% the Code Analyzer in the MATLAB editor flags them.  In R2011a, the\n% warning directs you to a\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/math\/bsn94u0-1.html section of the % doc> that shows how to replace the old with the new.\n%\n% |RandStream| is still the tool to use for more complicated situations\n% involving multiple parallel random streams, so |rng| doesn't entirely\n% replace it.  But for most people, most of the time, |rng| is a much\n% simpler choice.\n\n##### SOURCE END ##### 5cc749b562984955a5131603dd8b8dc7\n--><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\nOnce again we're going to hear from guest blogger Peter Perkins, who is a statistical software developer here at The MathWorks.<br \/>\nMATLAB has had random numbers since the beginning. But not... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2011\/07\/07\/simpler-control-of-random-number-generation-in-matlab\/\">read more >><\/a><\/p>\n","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16,6,28],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/281"}],"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=281"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/281\/revisions"}],"predecessor-version":[{"id":1879,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/281\/revisions\/1879"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=281"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=281"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=281"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}