{"id":258,"date":"2010-12-21T04:54:39","date_gmt":"2010-12-21T04:54:39","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2010\/12\/11\/strings-and-numbers-as-arguments\/"},"modified":"2010-12-21T20:21:13","modified_gmt":"2010-12-21T20:21:13","slug":"strings-and-numbers-as-arguments","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2010\/12\/21\/strings-and-numbers-as-arguments\/","title":{"rendered":"Strings and Numbers as Arguments to Standalone Executables"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>Guest blogger <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/4660\">Peter Webb<\/a> returns with another in an <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/deployment\/\">occasional series<\/a> of postings about application deployment.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#2\">String Arguments<\/a><\/li>\r\n         <li><a href=\"#4\">Numeric Arguments<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>Most MATLAB functions take input arguments. When you create a <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f2-9676.html\">shared library or DLL<\/a> from a MATLAB function with <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/mcc.html\">MATLAB Compiler<\/a>, the generated library functions take the same number and type of arguments as the MATLAB functions. But what about a <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f7-996249.html\"><i>standalone executable<\/i><\/a>? How do you pass arguments to a MATLAB function that you've compiled into a complete program?\r\n   <\/p>\r\n   <p>On the UNIX or DOS command line, of course.<\/p>\r\n   <p>The main program generated by MATLAB Compiler examines the command line and passes any arguments to your <i>main<\/i> function, the function you listed first when you created the application with <tt>mcc<\/tt>. But UNIX and DOS don't understand MATLAB data types, so all they can do is pass the command line arguments to your program\r\n      as strings.\r\n   <\/p>\r\n   <p>For example, you might compile the function <tt>compute<\/tt> into a standalone executable and then run it with the argument <tt>17<\/tt>:\r\n   <\/p><pre> compute 17<\/pre><p>Your <tt>compute<\/tt> function receives the string <tt>'17'<\/tt> as its first input. If it is expecting a number, <tt>compute<\/tt> probably won't produce the correct result when invoked with a string.\r\n   <\/p>\r\n   <p>All is not lost, however. Simple modifications to your M-code can enable you to handle many different types of arguments.\r\n      Let's begin by looking at techniques for handling strings.\r\n   <\/p>\r\n   <h3>String Arguments<a name=\"2\"><\/a><\/h3>\r\n   <p>Since MATLAB Compiler generates code that passes strings on the command line to your program's main function, you don't need\r\n      to modify programs that accept string inputs. For example, here's a program that plots a histogram of the number of times\r\n      each letter in the alphabet appears in an input string. The function takes a single input and has zero outputs.\r\n   <\/p><pre>function freq(msg)\r\n  % Remove spaces\r\n  msg(msg == ' ') = [];<\/pre><pre>  % Convert to lower case, and map the letters to numbers.\r\n  % a=1, b=2, etc.\r\n  msg = lower(msg) - double('a') + 1;<\/pre><pre>  % Map non-letter characters to zero.\r\n  msg(msg &lt; 1) = 0;\r\n  msg(msg &gt; 26) = 0;<\/pre><pre> % Display a histogram of the letter frequency in the message.\r\n  count = hist(msg, 27);\r\n  bar(0:26, count);\r\n  labels = char([double('@'), double('a'):double('z')])';\r\n  set(gca, 'XTick', 0:26+0.5, 'XTickLabel', labels);\r\n axis tight<\/pre><p>First, compile the program to a standalone executable:<\/p><pre>mcc -mv freq<\/pre><p>Run it with a string argument:<\/p><pre>freq \"The quick brown fox jumps over the lazy dog!\"<\/pre><p>The histogram is surprisingly uniform.<\/p>\r\n   <p>\r\n      <img decoding=\"async\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/258\/fox.jpg\" height=\"400\" \/>\r\n      \r\n   <\/p>\r\n   <h3>Numeric Arguments<a name=\"4\"><\/a><\/h3>\r\n   <p>The <a href=\"http:\/\/en.wikipedia.org\/wiki\/Ulam_spiral\">Ulam spiral<\/a> reveals patterns in the distribution of prime numbers. The MATLAB function <tt>ulam<\/tt> below, displays an Ulam spiral as an <i>NxN<\/i> black and white image.\r\n   <\/p><pre>function ulam(n)\r\n  % Compute the NxN ulam spiral\r\n  u = spiral(n);<\/pre><pre>  % Set p(i,j) to 1 iff u(i,j) is prime.\r\n  p = isprime(u);<\/pre><pre>  % Display the results: primes as white pixels\r\n  image(p);\r\n  colormap([0 0 0; 1 1 1]);\r\n  axis off<\/pre><p>Create a standalone executable <tt>ulam<\/tt> with MATLAB Compiler:\r\n   <\/p><pre>mcc -mv ulam.m<\/pre><p>Run the executable to display a 200x200 Ulam spiral:<\/p><pre>ulam 200<\/pre><p>Not so fast! <tt>ulam<\/tt> reports an error:\r\n   <\/p><pre>??? Error using ==&gt; zeros\r\nTrailing string input must be a valid numeric class name.<\/pre><pre>Error in ==&gt; spiral at 9<\/pre><p>If I modify the <tt>ulam<\/tt> MATLAB function to expect a string, by calling <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/ref\/str2double.html\"><tt>str2double<\/tt><\/a> on the input <tt>n<\/tt>, calling <tt>ulam<\/tt> in MATLAB will be awkward:\r\n   <\/p><pre> ulam('200');<\/pre><p>Therefore, <tt>ulam<\/tt> needs additional logic when it is running as a deployed application. There's a function for that -- <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/isdeployed.html\"><tt>isdeployed<\/tt><\/a> -- which returns <tt>true<\/tt> only when run in a deployed application. I can test for <i>deployed mode<\/i>, and then convert <tt>n<\/tt> from a string into a double, like so:\r\n   <\/p><pre>  if isdeployed\r\n     n = str2double(n);\r\n  end<\/pre><p>Alternatively, I could test to see if <tt>n<\/tt> is a character string using <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/ref\/ischar.html\"><tt>ischar<\/tt><\/a>:\r\n   <\/p><pre>  if ischar(n)\r\n      n = str2double(n);\r\n  end<\/pre><p>Add either of these tests as the first three lines of the <tt>ulam<\/tt> function, and recompile. Now <tt>ulam 200<\/tt> generates an intriguing image. (Why do the primes seem to line up on the diagonals?)\r\n   <\/p>\r\n   <p>\r\n      <img decoding=\"async\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/258\/ulam.jpg\" height=\"400\" \/>\r\n      \r\n   <\/p>\r\n   <p>In a later posting, I'll demonstrate how to pass cell arrays and other MATLAB data types to your standalone applications.\r\n      In the meantime, if you have questions or comments, let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=258#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_91c219657daa4a7881bc11991370e8fd() {\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='91c219657daa4a7881bc11991370e8fd ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 91c219657daa4a7881bc11991370e8fd';\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 = 'Peter Webb';\r\n        copyright = 'Copyright 2010 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_91c219657daa4a7881bc11991370e8fd()\"><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.11<br><\/p>\r\n<\/div>\r\n<!--\r\n91c219657daa4a7881bc11991370e8fd ##### SOURCE BEGIN #####\r\n%% Strings and Numbers as Arguments to Standalone Executables\r\n% Guest blogger \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/4660 Peter Webb>\r\n% returns with another in an \r\n% <https:\/\/blogs.mathworks.com\/loren\/category\/deployment\/ occasional series>\r\n% of postings about application deployment. \r\n\r\n%%\r\n% Most MATLAB functions take input arguments. When you create a \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f2-9676.html\r\n% shared library or DLL> from a MATLAB function with  \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/mcc.html \r\n% MATLAB Compiler>, the generated library functions take the same number\r\n% and type of arguments as the MATLAB functions. But what about a\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f7-996249.html \r\n% _standalone executable_>? How do you pass arguments to a MATLAB function\r\n% that you've compiled into a complete program? \r\n%\r\n% On the UNIX or DOS command line, of course. \r\n%\r\n% The main program generated \r\n% by MATLAB Compiler examines the command line and passes any arguments\r\n% to your _main_ function, the function you listed first when you created\r\n% the application with |mcc|. But UNIX and DOS don't understand MATLAB data\r\n% types, so all they can do is pass the command line arguments to your\r\n% program as strings.\r\n%\r\n% For example, you might compile the function |compute| into a standalone\r\n% executable and then run it with the argument |17|:\r\n% \r\n%   compute 17\r\n%\r\n% Your |compute| function receives the string |'17'| as its first input.\r\n% If it is expecting a number, |compute| probably won't produce the\r\n% correct result when invoked with a string.\r\n%\r\n% All is not lost, however. Simple modifications to your M-code can enable you to\r\n% handle many different types of arguments. Let's begin by looking at\r\n% techniques for handling strings.\r\n\r\n%% String Arguments\r\n% Since MATLAB Compiler generates code that passes strings on the\r\n% command line to your program's main function, you don't need to modify\r\n% programs that accept string inputs. For example, here's a program that\r\n% plots a histogram of the number of times each letter in the alphabet\r\n% appears in an input string. The function takes a single input and has\r\n% zero outputs.\r\n%\r\n%  function freq(msg)\r\n%    % Remove spaces\r\n%    msg(msg == ' ') = [];\r\n%    \r\n%    % Convert to lower case, and map the letters to numbers.\r\n%    % a=1, b=2, etc. \r\n%    msg = lower(msg) - double('a') + 1;\r\n%    \r\n%    % Map non-letter characters to zero.\r\n%    msg(msg < 1) = 0;\r\n%    msg(msg > 26) = 0;\r\n%    \r\n%   % Display a histogram of the letter frequency in the message.\r\n%    count = hist(msg, 27);\r\n%    bar(0:26, count);\r\n%    labels = char([double('@'), double('a'):double('z')])';\r\n%    set(gca, 'XTick', 0:26+0.5, 'XTickLabel', labels);\r\n%   axis tight\r\n    \r\n%%\r\n% First, compile the program to a standalone executable:\r\n%\r\n%  mcc -mv freq\r\n%\r\n% Run it with a string argument:\r\n%\r\n%  freq \"The quick brown fox jumps over the lazy dog!\"\r\n%\r\n% The histogram is surprisingly uniform.\r\n%\r\n% <html>\r\n% <img decoding=\"async\" src=\"fox.jpg\" height=\"400\" \/>\r\n% <\/html>\r\n    \r\n\r\n%% Numeric Arguments\r\n% The <http:\/\/en.wikipedia.org\/wiki\/Ulam_spiral Ulam spiral> reveals\r\n% patterns in the distribution of prime numbers. The MATLAB function |ulam|\r\n% below, displays an Ulam spiral as an _NxN_ black and white image.\r\n%\r\n%  function ulam(n)\r\n%    % Compute the NxN ulam spiral\r\n%    u = spiral(n);\r\n%    \r\n%    % Set p(i,j) to 1 iff u(i,j) is prime.\r\n%    p = isprime(u);\r\n%    \r\n%    % Display the results: primes as white pixels\r\n%    image(p);\r\n%    colormap([0 0 0; 1 1 1]);\r\n%    axis off\r\n    \r\n\r\n%%\r\n% Create a standalone executable |ulam| with MATLAB Compiler:\r\n%\r\n%  mcc -mv ulam.m\r\n%\r\n% Run the executable to display a 200x200 Ulam spiral:\r\n%\r\n%  ulam 200\r\n%\r\n% Not so fast! |ulam| reports an error:\r\n%\r\n%  ??? Error using ==> zeros \r\n%  Trailing string input must be a valid numeric class name. \r\n%\r\n%  Error in ==> spiral at 9 \r\n%\r\n% If I modify the |ulam| MATLAB function to expect a string, by calling \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/ref\/str2double.html\r\n% |str2double|> on the input |n|, calling |ulam| in MATLAB will be awkward:\r\n%\r\n%   ulam('200');\r\n%\r\n% Therefore, |ulam| needs additional logic when it is running as a deployed\r\n% application. There's a function for that REPLACE_WITH_DASH_DASH  \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/isdeployed.html\r\n% |isdeployed|> REPLACE_WITH_DASH_DASH which returns |true| only when run in a deployed\r\n% application. I can test for _deployed mode_, and then convert |n| from a\r\n% string into a double, like so:\r\n%\r\n%    if isdeployed\r\n%       n = str2double(n);\r\n%    end\r\n%%\r\n% Alternatively, I could test to see if |n| is a character string using\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/ref\/ischar.html\r\n% |ischar|>:\r\n%\r\n%    if ischar(n)\r\n%        n = str2double(n);\r\n%    end\r\n%%\r\n% Add either of these tests as the first three lines of the |ulam|\r\n% function, and recompile. Now |ulam 200| generates an intriguing image.\r\n% (Why do the primes seem to line up on the diagonals?)\r\n%\r\n% <html>\r\n% <img decoding=\"async\" src=\"ulam.jpg\" height=\"400\" \/>\r\n% <\/html>\r\n% \r\n% In a later posting, I'll demonstrate how to pass cell arrays and other\r\n% MATLAB data types to your standalone applications. In the meantime, if\r\n% you have questions or comments, let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=258#respond here>.\r\n\r\n##### SOURCE END ##### 91c219657daa4a7881bc11991370e8fd\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Guest blogger Peter Webb returns with another in an occasional series of postings about application deployment.\r\n      \r\n   \r\n   Contents\r\n   \r\n      \r\n   ... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2010\/12\/21\/strings-and-numbers-as-arguments\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/258"}],"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=258"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/258\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=258"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=258"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=258"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}