University of Alaska Fairbanks
Geophysical Institute

Beyond the Mouse 2010 - The geoscientist's computational chest.

3. (Advanced) Variables and Functions - Matlab I

"Programming is legitimate and necessary academic endeavor."
Donald E. Knuth

Review on variables (assignments vs. referencing), Variables in Matlab, Writing your own functions in Matlab.

Lecture

Variables and Functions (pdf)

Be careful when creating structs that are supposed to contain cell-arrays! Here is an example that explains the odd behavior that I describe in the text below. Note, that this is well documented Matlab behavior and therefore not a bug, but a feature.

The problem is with creating fields that hold cell arrays. If you create a struct and one of the field values is a cell array, Matlab will create an array of structs, each holding one value of the cell array as value of the respective field. If you want to have a cell array as value of one of your fields, you have to hand it to the struct as a _single_ cell. I find this behavior very irritating and unintuitive. But Mathworks say:

``Note: When calling the struct function, use one set of curly braces {} to pass multiple field values, and use two sets of curly braces {{}} to create a cell array in the specified field.''

BECAUSE: ``The MATLAB curly braces {} operator constructs a cell array. One use of cell arrays is as a convenient way to pass arguments when calling a function. This is exactly how they are used with the struct function. When you use this operator to pass multiple field values to the struct function, you are actually passing these values packaged in a cell array. The struct function, upon receiving the cell array argument, removes the field values from the cell array and assigns them to the fields specified in your struct command.'' (from http://www.mathworks.com/help/techdoc/matlab_prog/br04bw6-38.html)

Keep this in mind whenever you're stuffing a cell array into a struct getting an extra layer of data organization you didn't ask for.

LAB 03

Structs, Cells, and Functions

Examples

Given in slides for the lecture.

Exercise:

Think about which parts of your flow charts can be implemented as functions and come up with necessary input parameters and return values. It might be good idea to do this in form of a table, example:

function definitioninput value(s)return value(s)
[str, errmsg] = sprintf(format, A, ...) format: String in single quotation marks that describes the format of the output fields.
A: numeric or character array.
returns results to string str and an error message string when the operation is unsuccessful. Otherwise, errmsg is empty.

ronni <at> gi <dot> alaska <dot> edu | last changed: September 28, 2010