\documentclass{article}[10pt]

\topmargin -0.5in
\textheight 9in
\oddsidemargin=-0.05in
\evensidemargin=-0.05in
\textwidth 6.5in
\pagestyle{empty}


\begin{document}
\title{Math 56: MATLAB vs python code example}
\date{\empty}
\author{Alex Barnett, \today}
\maketitle

MATLAB and python are quite similar (both high-level interpreted languages that
can be interactive, or use script or function files).
Going back and forth is like going from Spanish to Italian.
Main differences: MATLAB has trailing semicolons to prevent output,
has {\tt end} to close conditionals or loops;
python uses {\em indentation} (leading spaces)
to indicate a conditional or looped
block (no {\tt end}), colon to start the block.
Array indexing is also different.
To help you, here's the same code in both. Please study them, and the simple
algorithm itself (a variant will come up on Tuesday 5/7/13).

\vspace{2ex}

\noindent \begin{minipage}[t]{3.1in}

{\bf MATLAB version}

\begin{verbatim}
function printbinary(n)
% printbinary(n) prints integer n in binary

if n<0, error('n cannot be negative'), end
if n==0, fprintf('0\n'); return, end

% t is largest power of 2 not exceeding n
t = 2^floor(log(n)/log(2));

while t>=1
  if n>=t, fprintf('1'), n = n-t;
  else, fprintf('0')
  end
  t = t/2;
end
fprintf('\n')    % terminate the string
\end{verbatim}

The above must be a file called {\tt printbinary.m}.
Here's its test script (a separate file, but you could put it in the
same file if you made it a function too):

\begin{verbatim}
% test the printbinary function
disp('the following two should match')
n = 153637;
printbinary(n)
dec2bin(n)
for n=0:10, printbinary(n); end    % a loop
try, printbinary(-4)   % should fail nicely
catch, 'n<0 error correctly detected', end
\end{verbatim}

Note the use of {\tt try} and {\tt catch} to test error reporting
without halting the program.

Can you spot a place in the code for improvement in reliability
at large {\tt n} ?

\end{minipage}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\hfill  % stay on same line
\begin{minipage}[t]{3.1in}

{\bf python version}

\begin{verbatim}
from math import *      # needed for logarithm

def printbinary(n):
    """printbinary(n), print integer in binary
    """
    if n<0:
        print 'n cannot be negative'; return
    if n==0:
        print '0'; return
    # t is largest power of 2 not exceeding n
    t = 2**floor(log(n)/log(2))
    s = ''            # output string
    while t>=1:
        if n>=t: s = s+'1'; n = n-t  # appends
        else: s = s+'0'
        t = t/2
    print s

# main script, run if imported/reloaded, etc
print 'the following two should match'
n = 153637; printbinary(n); print bin(n)
for n in range(11):  # loops from 0 to 11-1=10
    printbinary(n)
printbinary(-4)      # should fail gracefully
\end{verbatim}

Say this file is named {\tt pb.py}.
You can run in two ways:
1) from the UNIX/Mac terminal via {\tt python pb.py},
or 2) from the python interactive environment
via {\tt execfile("pb.py")}.
The latter is closest to running a Matlab script,
since the variables are still accessible,
useful for debugging.
You can also 3) {\tt import pb} which loads it
as a {\em module}, then run {\tt pb.printbinary(...)}.
Modules are the way to build bigger packages.
For changes to take effect you must {\tt reload(pb)}.

Notice use of a ``docstring'' for documentation;
once imported, typing {\tt help pb.printbinary} shows it.
\end{minipage}

\end{document}
