Skip to content

Commit

Permalink
Update 3
Browse files Browse the repository at this point in the history
  • Loading branch information
hendri54 committed Jan 11, 2016
1 parent 4a41218 commit 62280fa
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 29 deletions.
28 changes: 22 additions & 6 deletions matlab_datatypes.mmd
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ These are really vectors of characters to Matlab.

Then there are more specialized datatypes such as `tables`.

You can also define your own data types. We will talk about that more later (object oriented programing).
You can also define your own data types. We will talk about that more later (see [object oriented programming][oop]).

The type of a variable is **not fixed**.

The following is perfectly fine code (and a popular source of errors).

```matlab
a = 1;
a = 'a string';
```

is perfectly fine code (and a popular source of errors).

## Vectors

To create a vector, simply fill it with values:
Expand Down Expand Up @@ -95,6 +95,14 @@ Then there is [logical indexing](http://blogs.mathworks.com/steve/2008/01/28/log

See also the [find](http://www.mathworks.com/help/matlab/ref/find.html) function for a similar idea.

#### Exercises ####

Start with `x = 1 : 3 : 30`.

1. Find all even elements.
2. Find all elements between 5 and 20.
3. Set all even elements to their negative values.

## Matrices

A matrix is an n-dimensional array of numbers.
Expand Down Expand Up @@ -202,10 +210,19 @@ Sub-matrices work just like ordinary 2-dimensional matrices.

But: `a(:,1,:)` is not a 2D matrix. It's a 3D matrix with a singleton 2nd dimension.

### Matrix Exercises ###

1. Construct a matrix `A` with elements `[2,4,...,20]` in row 1 and `[1,4,7,...,28]` in row 2.
2. Replace row 1 with its square.
3. Find all columns where row 1 > row 2.
4. Let `x=ones(10,1)`. Compute `Ax`.

## Structures

Structures are containers for variables of different types.

They are defined by simply adding element to a blank structure.

#### Example:

Store the contact information for a person.
Expand All @@ -215,8 +232,6 @@ Store the contact information for a person.
contactS.Age = 37;
```

A structure is defined by assigning values to it.

The elements are accessed by name:

```matlab
Expand Down Expand Up @@ -342,4 +357,5 @@ uint8

> Rule of thumb: Store large datsets in low precision. Make everything double the moment you load it.

-----------

[oop]: oop.html
24 changes: 13 additions & 11 deletions matlab_editing.mmd
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,42 @@
## The Editor

Matlab has a built-in editor.

Benefit: Integration with the command processor.
When a crash occurs, you can inspect variables in the editor.

### Editor Tips ###

Cell mode
[Cell mode](http://www.mathworks.com/help/matlab/matlab_prog/run-sections-of-programs.html)

* Start a line with `%%` and it becomes a collapsible `cell`. That makes moving around the editor easier.
* One can do other things with cells (e.g., run a portion of code; collapse it; etc.)

Comments

* Use **lots** of comments to make your code readable.

* Block comments are enclosed with `%{...%}`

Mlint
[Mlint](http://www.mathworks.com/help/matlab/matlab_prog/check-code-for-errors-and-warnings.html)

* highlights questionable syntax or errors

## Debugging

Debugging means locating program errors.

####keyboard command
#### `keyboard` command

A useful command for debugging is `keyboard`.
A useful command for debugging is [keyboard](www.mathworks.com/help/matlab/ref/keyboard.html).
It halts program execution and returns the user to the command line.
Any commands can then be executed as if the program itself contained those commands.
In particular, one can inspect the values of all local variables.
Setting **break points** has a similar effect.

####Debugging mode
Setting [break points](http://www.mathworks.com/help/matlab/matlab_prog/debugging-process-and-features.html) has a similar effect.

#### Debugging mode

Matlab can switch to a debugging mode that allows the user to inspect the
state of a program when it crashes.
Matlab can switch to a debugging mode that allows the user to inspect the state of a program when it crashes.

To switch on debugging mode, type `dbstop error`

Expand All @@ -54,6 +55,8 @@ This stops the program.
Write **test functions** for every sub-routine you write.
Never assume that a new program will run correctly.

Write a `test_all` functions that runs all the tests in one go.

Embed **self-test code** in your programs.

#### Check everything you can.
Expand All @@ -66,7 +69,6 @@ Embed **self-test code** in your programs.

By checking all the time, errors are spotted as early as possible which makes them much easier to fix.

See `validateattributes` for an easy way of implementing all of this.

See [validateattributes](www.mathworks.com/help/matlab/ref/validateattributes.html) for an easy way of implementing all of this.

---------------
42 changes: 30 additions & 12 deletions matlab_functions.mmd
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
# Matlab: Functions and Scripts

**Scripts** are simply collections of commands that are run as if they were typed at the command prompt.
[Scripts](http://www.mathworks.com/help/matlab/matlab_prog/create-scripts.html) are simply collections of commands that are run as if they were typed at the command prompt.

* They are rarely used b/c their contents is not *encapsulated*.
* They are rarely used b/c their contents is not [encapsulated](https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)).
* Any variables defined in a script show up in the [global workspace](http://www.mathworks.com/help/matlab/ref/global.html).
* In the section on [structured programming](programming.html#structured-programming), we talk about why this is bad.

**Functions** are similar to scripts with one crucial difference:
[**Functions**](http://www.mathworks.com/help/matlab/ref/function.html) are similar to scripts with one crucial difference:

* All variables inside a function are **private**.
* Other functions cannot see the variables inside a function (*encapsulation*).
* Any variable a function should know must be passed to it as an input argument.
* Any variable to be retained after the function finishes must be passd out of it as a return argument.
* Any variable to be retained after the function finishes must be passed out of it as a return argument.

> Always use functions, never scripts!

Expand All @@ -29,7 +31,7 @@ Now try `open zeros`. This opens `zeros.m`.

## The Matlab Path <a name="mpath"></a> ##

Matlab commands are stored in text files with the extension ''m''.
Matlab commands are stored in text files with the extension `m`.

When the user issues a command, such as `m = zeros([3,4]))`, Matlab searches
for a matching m-file, in this case `zeros.m` and runs it.
Expand All @@ -43,15 +45,15 @@ In case you wonder, this is done as a `cell array` of strings.

You can see what's on the path by typing `path`.

You add directories to the path with `addpath`.
You add directories to the path with [addpath](http://www.mathworks.com/help/matlab/ref/addpath.html).

In addition, Matlab searches the current directory (the one shown in the file browser).

Therefore, every time you write new code, you need to put the directories on the `path` before the code can be called.

There is no way to allow one function to access some code without changing the `path` globally. This differs from other languages. It makes it hard to organize code.

Every project therefore needs a startup routine that adds its directory to the Matlab path.
Every project therefore needs a **startup routine** that adds its directory to the Matlab path.
Or its program files need to be placed in the current working directory.

## Organizing Code ##
Expand All @@ -67,9 +69,9 @@ Then switch the current directory to that directory using `cd`.
2. For files that are **shared** between several projects, place them in a special directory (`blah/shared`).
Place this directory on the path: `addpath('blah/shared')` .

Over time you will write many general purpose routines that should be stored in this `shared` directory.
Over time you will write many general purpose routines that should be stored in this `shared` directory. Reusable code!

#### Name Conflicts ####
### Name Conflicts ###

Now you run into a problem: **name conflicts**.

Expand All @@ -81,9 +83,11 @@ There are 2 ways of ensuring this:

Such as `plot_821.m`

2. Packages: If you place an m-file into a directory that starts with `+`, let's say `+plot_821`, you can access it like this: `plot_821.plot(x)`.
2. Packages: If you place an m-file into a directory that starts with `+`, let's say `+econ821`, you can access it like this: `econ821.plot(x)`.

For this to work, the parent dir of `+plot_821` must be on the `path`.
For this to work, the parent dir of `+econ821` must be on the `path`.

This is also useful to organize your code within a project (which may contain hundreds of functions).


## Example of a Function
Expand Down Expand Up @@ -219,7 +223,7 @@ Household solves \\(\max u\left(c,g\right)\\)

subject to \\(y=c+s \\) and \\(g=z+sR\\)

A solution: \\(c,g,s\\)
A solution: $c,g,s$

that solve 2 budget constraints and Euler equation

Expand Down Expand Up @@ -315,4 +319,18 @@ function hh_x1(y, z, R, bb, sig)
end
```

## Exercises ##

1. Write a CES utility function that computes $u'(c)$ and $u(c)$.
2. Write a function that computes the inverse of $u'(c)$.
3. Write a test function that checks properties of the utility function:
4. The inverse of the inverse equals $u'(c)$.
5. Marginal utility is decreasing.

Extra credit:

1. Package all of that into an object (a user defined data type).
2. Now write all of this for $u(c)=e^{-\phi c}$.
3. In your test function, set things up so that you only need to change a single line of code to test both utility functions (the benefit of OOP in action).

----------

0 comments on commit 62280fa

Please sign in to comment.