Octave and commandline arguments
October 8, 2009 at 12:21 PM by Dr. Drang
I needed a script that would print the values of the probability mass function for the binomial distribution for any number of trials and any probability of success in an individual trial. I wanted to pass the number of trials and the probability in on the command line and get the PMF values back in a form compatible with Gnuplot; that is, I wanted to be able type this
binomial 10 .166667
and get back this
0 0.161505
1 0.323011
2 0.290710
3 0.155046
4 0.054266
5 0.013024
6 0.002171
7 0.000248
8 0.000019
9 0.000001
10 0.000000
(For 10 rolls of a standard sixsided die, the probability of getting 0 ones is 16.15%, the probability of getting 1 one is 32.30%, the probability of getting 2 ones is 29.07%, and so on.)
I decided to use Octave as my scripting language because it has a binomial PMF function built in (binopdf
^{1}). I’ve written scripts in Octave in the past, but I’ve never tried to pass arguments to those scripts and wasn’t sure how to do it.
It won’t surprise anyone with C/Shell/Perl/Python/Ruby experience to learn that the Octave function that grabs the commandline arguments is called argv
. It takes all the spaceseparated arguments and puts them in a cell array, a heterogeneous data structure comparable to a list in Perl/Python/Ruby. Cell arrays are distinguished from regular (homogeneous) arrays by the use of curly braces ({}) for indexing instead of straight brackets ([]). The arguments come in as strings, so if you want to pass in numbers (as I did), you’ll have to convert them.
Here’s the script I came up with
1: #!/usr/bin/env octave q
2:
3: n = str2num(argv(){1});
4: p = str2num(argv(){2});
5: x = 0:n;
6: pdf = [x; binopdf(x, n, p)];
7:
8: printf("%3d %f\n", pdf)
The shebang line includes the q
option to prevent Octave from printing its version and copyright information when it starts up. Lines 3 and 4 get the arguments and turn them into numbers. Line 5 creates the 1D array of success counts, and Line 6 uses that to create the 2D array of success counts and associated PMF values. Here you see one of Octave’s strengths: its ability to apply functions and operators to entire arrays at once—no need for map
or list comprehensions. Line 8 formats and prints the results.
With the script written—and made executable via chmod +x
—I could call it from within Gnuplot to generate data for plots like this
an example of how the binomial distribution tends toward the normal distribution for large numbers of trials.

Yes, Octave calls it
binopdf
even though it might be more appropriate to call itbinopmf
. I think the Octave people wanted naming consistency across all distributions, whether continuous or discrete. So all the cumulative distribution functions end with “cdf,” all the inverse CDFs end with “inv,” and all the density/mass functions end with “pdf.” ↩