You are on page 1of 2

Functions

The rand function creates random numbers in the range 0 and 1. The arguments are size of desired
random matrix.

The edit command opens the editor to write scripts.

You should name the file that contains the function with the function name, you can pick another name,
but it’ll get very confusing and it’s a very bad practice.

Function I/O

A variable that’s only accessible from within the function is called local variable. A local variable exists
only during the function call.

In latest versions of Matlab, the file is automatically saved if you click outside the editor tab.

There are 9 types of function declarations, consider reading them.

In the workspace, click on the box beside a variable to view it in spreadsheet.

V = a(:); is a special way to index in matlab. It brings all the elements in the matrix in one column vector.

The sum function calculates the sum of all the columns of a matrix and returns a row vector of the sums.

If a function has multiple returns and you receive less than that, the remaining returns will be thrown
away.

The returns are enclosed by [] and are separated by commas, but to receive returns the vars must also
be enclosed in [] but can be separated by commas or spaces.

If a functions returns are less than the number of receiving vars, matlab throws error.

Formal Definition of Functions

Watch Slide.

Subfunctions

Functions can call each other. You can also put multiple functions in one m file.

If you have more than one function in a file, either all of the functions should have end statement, or
neither of them should.

Only the first function, which has the same name as the file, can be called by other functions outside the
file.

Scope

Is the set of statements that can access a variable.

To set a global variable, use global <var name>. You cannot combine global var declaration with
assignment.

Don’t use global variables bcz they make errors hard to diagnose.
Advantage of Functions

Watch slide.

Scripts

It's important to note that a script is very different from a function. First, a script never returns a value
or accepts input arguments. And second, the scope of the script is the scope of the command window.

You can use file name with edit command, and it’ll create a new file and start editing it.

You might also like