CS150 - Fall 2012 - Class 22

  • video
       - http://www.youtube.com/watch?v=msaWXY3OuQQ

  • logical expressions

  • admin
       - Matlab lap prep due Friday

  • working directory
       - see the matlab basics handout
       - We can also just type in the working directory directly in the field in the left frame
          - as you type, it gives you suggests for how to continue

  • scripts
       - just like in Python we can write our own scripts/programs
       - You can generate a new script many different ways:
          - type: command+n
          - click on the "new script" button in the upper left corner of the matlab window
          - Select File->New->Script
       - This will bring up the "Editor"
          - by default it's a separate window however you can "Dock" the window within the rest of Matlab by clicking the "Dock editor" button (looks like an arrow going to the lower right)
       - The editor has a number of nice features we've seen before
          - syntax highlighting
          - auto-indenting
             - for Matlab indenting isn't mandatory, but we'll do it for good style
          - underlines syntax mistakes
          - underlines possible mistakes (i.e. warnings)
          - allows us to "run" the script
          - other features...
       - Just like Python, a Matlab script is just a set of statements
       - When you save the file file will have the .m extension (just like python had a .py extension)
       - What does the basic_script.m do in Matlab-examples code ?
          - four statements:
             - first: displays/prints the text
             - second: display the string as a result (so will show the ans = )
                - notice that unlike Python, even when running as a script, the variable is output
             - third: won't do anything since the line is terminated with a semi-colon
                - get in the habit of terminating the lines with semi-colons since this is the behavior you want most of the time
             - fourth: display another string
          - we've also put in some comments
             - what do you think the comments at the top do?
                - like module docstrings: we can use help and it will be returned

                >> help basic_script
                 this is a script. It runs a few statements
                 comparing different ways of outputting values

                - notice that unlike Python, help is immediately available to you without having to do something like import
       - We can run scripts different ways:
          - By clicking the green arrow
          - By typing the name of the script (i.e. the name of the file minus the .m)
             >> basic_script
             display some text

             ans =

             a string without a semicolon

             another display
       - What does guess_game.m do in Matlab-examples code ?
          - picks a random integer between 1 and 10
          - prompts the user to guess a number
             - input is similar to raw_input in python
                - it expects the user to enter a matrix
                - it could be a single value
                - it could be a string (though the user has to enter it with single quotes)
             - if the user doesn't enter anything, it prompts them again
                >> help isempty
                 ISEMPTY True for empty array.
                 ISEMPTY(X) returns 1 if X is an empty array and 0 otherwise. An
                 empty array has no elements, that is prod(size(X))==0.

                 Overloaded methods:

                 Reference page in Help browser
                 doc isempty
             - remember, we terminate our loops/control structues with "end"
          - checks if the number is too high, low, or correct and outputs the appropriate value
             - elseif and else terminate the block before
             - end terminates the final block

  • functions in Matlab
       - we can write our own functions, just like in Python
       - The syntax is:
          function return_variable = function_name(parameter1, parameter2, ...)
       - For example look at my_sqrt.m in Matlab-examples code
          function answer = my_sqrt(x)
          answer = x^0.5
       - A few interesting things to note:
          - like any language, we have a different syntax for defining functions
          - Matlab does not return values using a return statement
             - to return a value, you just assign to the variable that you declared in your function header as the "return" variable
             - this is a bit different than Python, but can be convenient
          - There is a return statement that doesn't take any parameters that just exits the function
             >> help return
  • multiple functions in a file
       - In many situations, you will only define one function per file
       - You can define multiple functions in a file:
          - The other functions are called "subfunctions"
          - subfunctions are NOT callable from outside the file (they are "private")
          - but if you need a helper function or some other functions that are not relevant to other people, you can include them
          - if you're helper function is in and of itself useful, then it should be in its own file

  • Reading from files and plotting
       - look at plot_file.m in Matlab-examples code
          - dlmread
             - reads numerical data in a file that is delimited by some value (e.g. a space, a tab, a comma)
                - if you just call it with the filename it tries to guess the delimiter
                - you can optionally specify the delimiter as the second parameter
             - reads the file all at once and returns a matrix
             - if the file contains non-numerical data or is not a proper matrix, you will get an error
          - plotting in Matlab is very similar to plotting with matplotlib
             - "plot" works similarly
             - other functions
                - title
                - xlabel
                - ylabel
                - ...
             - some differences
                - unlike matplotlib there is now "show" call when we're done adding stuff to the figure
                - by default, each time plot is called, regenerates the plot
                - you can change this behavior by adding "hold all"
                   - tells Matlab to not generate a new plot, but to add each plot command on the same graph
                   - (see help hold) for more details
          - What do we plot?
             - plots each column, 2 through the end, as the y values and the first column as the x values
                >> plot_file('data.txt')
                >> plot_file('data2.txt')
       - There are many other variations on reading from files
          - see help dlmread for some more complicated examples
          - for even more flexibility see the textscan function (and look at examples in the documentation online)

  • Writing to a file
       - Writing to a file is also easy and can be done a matrix at a time using dlmwrite
          - by default uses space as a delimiter, though can specify others
       - There are also some nice features in Matlab for saving your workspace (or particular variables in your workspace)
          - see save and load

  • matlab performance (didn't cover in class, but if you're curious)
       - look at matrix_add.m in Matlab-examples code
          - what does the function do?
             - check to make sure that the matrices are the same size
                - note that size actually returns a matrix, but we can still ask if two matrices are equal
             - for each row
                 - for each column of each row
                   - add the i, j value of a and b and store it in m
             - adds each entry of the matrix together
          - let's look at how fast this function is:
             >> matrix_add(ones(10000), ones(10000));
             - takes ~15 seconds to run
          - if we compare this to the built-in function
             >> ones(10000) + ones(10000);
             - takes < a second to run
          - Just like R...
             - Matlab is optimized to work on matrices
             - you should avoid for loops if you can
                - often there is a much better way of doing it without a for loop (though sometimes you have to get sneaky)