PHYS 210 2014: Homework 3 Help page

As you work through the current homework I will be more closely monitoring your collective progress than for the previous assignments and on the basis of what and how you are doing, I will continue to post tips and hints that may be of use.

As with the bugs page, entries are listed in reverse chronological order.

Table of Contents

      
 
 
 
 
 
 
 
 
 

1 Utility Matlab functions and bash scripts (commands)

As I discussed briefly in the Nov 5 lab, I have coded a few utilities that you may find some use for while finishing Homework 3 and your term projects. They are

1.1 Using lookfor to locate PHYS210-specific Matlab code

Execute this command in the Matlab command window

I'm slowly editing the 100+ .m files that are specific to this course so that they all contain PHYS210 in the H1 line (first comment line after the function header which, noting that lookfor uses a case-insensitive search means that you can use

>> lookfor phys210

to locate all scripts/functions that I've labelled with PHYS210 thus far.

I am also sub-categorizing the H1 lines so that you can type

>> lookfor phys210-<topic>

to find scripts/functions pertaining to <topic>. Currently the following topics are implemented:

  1. bs: binary search
  2. demo: miscellaneous demonstration
  3. hw3: specific to Homework 3
  4. pendulum: nonlinear/linear pendula simulations
  5. util: utility

1.2 cdm: Matlab function to change to your Matlab directory

Execute this function in the Matlab command window

Here's the definition:

>> type cdm

function cdm
% cdm Changes working directory to /phys210/$USER/matlab [PHYS210-util]
   cd(sprintf('/phys210/%s/matlab', getenv('USER')));
   fprintf('Current working directory: %s\n\n', pwd);
   fprintf('Directory listing follows:\n\n');
   ls;
end

And here's how it works:

>> cdm

Current working directory: /phys210/phys210f/matlab

Directory listing follows:

hello.m  myaddsub.m  omega0crit.dat  pwrsout.dat   q1.m
myadd.m  myvec.m     onearg.m        pwrsout1.dat  twoargs.m

1.3 decomment: Strips comments and whitespace/empty lines from .m files

Execute this command in a shell (terminal window)

If you find all of my comments in the template files that I have provided annoying, distracting etc., you can use this command to read the file, remove the comments and whitespace lines and dump what remains on standard output.

Example

# Using the command without any arguments will generate a usage
# message.

% decomment

    usage: decomment [-hnxtw] [-c <char>] file ... 

    Displays and counts number of non-comment/non-whitespace/non-empty 
    lines in files.

    options:

    -h          ---   Display this usage message.
    -n          ---   Suppress line count.
    -x          ---   Suppress de-commented text display. 
    -t          ---   Display total line count.
    -w          ---   Display whitespace and empty lines.
    -c <char>   ---   Use <char> for comment character (default #)

    Automatically uses comment characters for files with certain extensions
    as follows (-c overrides):

    .m          ---   %
    .f          ---   c
    .F          ----  c
    .f90        ----  c

# Now use it.

% cd ~phys210/matlab

# First display the whole file, comments and all.

% cat bslow.m

function bslow(verbose)
% bslow Replaces low value of binary search bracket with midpoint [PHYS210-bs]
%
% Updates low value: then displays bracket and new midpoint.
% Supplying zero 0 for optional verbose argument suppresses output.
   global Bs_low Bs_high Bs_tol Bs_progress;
   if ~ bsinitialized
      warning('Search not initialized.  Use bsnew(low, high)');
      return;
   end
   Bs_low(end+1) = bscurrent;
   Bs_progress(end+1) = 0;
   if nargin == 0 || length(verbose) ~= 1 || verbose
      bsbracket;
   end
end

# Now strip out the comments: note, the output is to standard out 
# i.e. the terminal.

% decomment bslow.m

function bslow(verbose)
   global Bs_low Bs_high Bs_tol Bs_progress;
   if ~ bsinitialized
      warning('Search not initialized.  Use bsnew(low, high)');
      return;
   end
   Bs_low(end+1) = bscurrent;
   Bs_progress(end+1) = 0;
   if nargin == 0 || length(verbose) ~= 1 || verbose
      bsbracket;
   end
end
bslow.m: 12 lines

Note that by default decomment also outputs a line telling you how many lines of code it displayed. This can be suppressed using the -n option so, for example, should you want to start your version of mbounce.m with no comments, you could execute

% cdhw3
% cd a4
% decomment -n ~phys210/matlab/bounce.m > mbounce.m

% cat mbounce.m

tmax = 3;
deltat = 0.01;
kappa = 0.98;
g = -20;
a = [0.0, g];
x0 = 0.0;
y0 = 1.0;
r = [x0, y0];
vx0 = 0.5;
vy0 = 0.0;
v = [vx0, vy0];
nbounce = 0;
plotenable = 1;
pausesecs = 0.01;
ballsize = 15;
ballcolor = 'r';
                                .
                                .
                                .
   if ( r(2) + dr(2) < fxy(2,1) )  &  ( fxy(1,1) <= r(1) & r(1) <= fxy(1,2) )
      v(2) = - kappa * v(2);
      dr(2) = 0;
      nbounce = nbounce + 1;
   end 
   r = r + dr;
end
if avienable
   close(aviobj);
   fprintf('Created video file: %s\n', avifilename);
end

where the vertical ellipsis (three dots) indicates that some lines have been omitted in the output from cat.

1.4 no-terminator: Displays lines in a .m file that aren't terminated with a ;

Execute this command in a shell (terminal window)

This script can be useful for identifying those statements (lines) in a .m file that don't end with a semi-colon terminator. As I have emphasized in the handout, unless otherwise specified all statements in all the scripts and functions you submit must end in semi-colons so that no extraneous output is generated.

This applies to your term project code as well as your code for this homework.

no-terminator can help you ensure that this is the case, and, more generally help you to find statements that are generating output and which can sometimes be hard to locate.

As with decomment, using the command with no arguments produces a usage message:

% no-terminator

usage: no-terminator [-hnC] file [file ...]

Outputs lines in Matlab/Octave files that are not terminated with a ;

Includes line numbers by default.

Always excludes comment and empty/whitespace lines (multiline 
comments not handled yet).

By default also excludes control structure and continuation lines:

   function
   return
   end
   if
   else
   elseif
   for 
   while
   break
   continue
   ...

Options

-h       -- Display this usage message.
-n       -- Don't display line numbers.
-c       -- Don't exclude control structure lines.

WARNING! This script is NOT robust. It WILL display false 
positives --- i.e. lines that don't end with a ; but which
should NOT end with one.  With luck, there will be a minimum
of false negatives, i.e. lines that COULD be terminated but 
aren't, which are those that the script is designed to detect.

As the usage message implies, the script doesn't report missing semi-colons in many of the cases where they aren't required (or would be syntactically invalid), typically because the statement is a function header or part of a control structure. For example, there is never any need to put a semi-colon after an end.

Example

# Display the contents of the `.m` file.

% cat bshigh.m

function bshigh(verbose)
% bshigh Replaces high value of binary search bracket with midpoint [PHYS210-bs]
%
% Updates high value: then displays bracket and new midpoint.
% Supplying zero 0 for optional verbose argument suppresses output.
   global Bs_low Bs_high Bs_tol Bs_progress;
   if ~ bsinitialized
      warning('Search not initialized.  Use bsnew(low, high).');
      return;
   end
   Bs_high(end+1) = bscurrent
   Bs_progress(end+1) = 1
   if nargin == 0 || length(verbose) ~= 1 || verbose
      bsbracket
   end
end

# Display the offending lines with line numbers.

% no-terminator bshigh.m

::::::::::::::
bshigh.m
::::::::::::::
11:    Bs_high(end+1) = bscurrent
12:    Bs_progress(end+1) = 1
14:       bsbracket

2 Web page technique: Link an image to a video

One of you was asking how to incorporate mbounce.avi into your web page some way other than just having some text that links to the AVI file.

Actually embedding the video in the page so that, for example, it comes up and running is probably more trouble than its worth, so I suggest the following technique.

Modify your mbounce script so that it saves the first "frame" of the video as a JPEG file, incorporate the image into your web page, and then make the image link to the movie file.

I've added a slightly modified version of bounce.m, called bounce_jpeg.m, to the course Matlab code base that illustrates the technique.

You can see the source code here: bounce_jpeg.m. The added comments explain what I've done.

Click HERE to see a page that uses this technique.

3 CRUCIAL!! How Matlab functions return values

Some of you are coding functions using a Maple-esque syntax, i.e. something like

function val = mymax2_bad(x, y)
    if x > y
        x
    else
        y
    end
end

if the task were to be to code a function that returns the maximum of its two input arguments.

Although this is the correct approach in Maple, is not in Matlab, where we need something like

function val = mymax2_good(x, y)
    if x > y
        val = x;
    else
        val = y;
    end
end

3.1 Detailed explanation

I have composed a detailed explanation of this issue which is available by clicking on the above heading and which has also been linked into the Matlab programming labs notes.

I suggest that you read through that explanation should you be having problems getting your functions to work properly, but here's the executive summary:

3.2 Executive summary

  1. In a generic function definition

    function [ <outarg1>, <outarg2>, ... <outargn> ] = <function name>(<inarg1>, ...)
    

    the <outargi> are the output arguments, or outargs.

  2. In the function body treat all of the outargs as local variables that can be used exactly like any other Matlab variables. Local means the same thing that it did in Maple, i.e. that only the function knows about the existence of its local variables and they will not conflict with variables with the same names that are used in other functions or scripts. with variable

  3. Ensure that each and every outarg has a value assigned to it before the function returns, which will happen either when execution reaches the end of the function definition is reached, or when an explicit return statement is encountered.

    That is, each and every outarg must appear on the left hand side of at least one assignment statement.

    Nothing stops you from reassigning the outarg one or more times in the function body so that it appears on the LHS of more than one assignment statement, but it must be assigned at least once, or the function definition is incorrect.