CS150 - Fall 2011 - Class 22

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

  • logical expressions

  • admin
       - Matlab lap prep due Friday
       - go/codegolf

  • working directory
       - see the matlab basics handout
       - We can also just type in 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 does 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:
                 timer/isempty
                 tscollection/isempty

                 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: sqrt
          function answer = sqrt(x)
             
          answer = x^0.5
       
       - A few interesting things to note:
          - like any language, we have a different syntax for definition 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
       
       - look at reverse.m in Matlab-examples code
          - in this case "result" is our return variable, so we assign to it to return the result
          - how does the function work?
             - end:-1:1 gives a vector with indices starting at the last up through 1
                - for example:
                >> 10:-1:1

                ans =

                 10 9 8 7 6 5 4 3 2 1

             - We then grab these indices from v, which reverses the list
                - for example:
                   >> x = [10, 11, 12]

                   x =

                    10 11 12

                   >> x([1, 2, 3])

                   ans =

                    10 11 12

                   >> x([3, 2, 1])

                   ans =

                    12 11 10

                   >> x([3, 3, 3])

                   ans =

                    12 12 12

  • Parameter passing in matlab
       - are vectors mutable?
          - yes
          >> x = [1, 2, 3];
          >> x(1) = 5

          x =

           5 2 3

       - in Python we said every variable was a reference to an object
       - How could we see if the same is true for Matlab?
          >> x = [1, 2, 3];
          >> y = x;
          >> y(1) = 5
          >> x
          
          x =

           1 2 3

          - not all languages treat things the same!
       - Given this, what would test_parameter_passing.m from Matlab-examples code do here:
          >> x = [1, 2, 3];
          >> test_parameter_passing(x)
          >> x
          
          x =

           1 2 3

          - we also get copies of matrices when they are passed as parameters
          - note that test_parameter_passing does NOT return a value so we don't need the 'variable ='

  • 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 ~10 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)