# Chapter 2: Basic MATLAB Concepts

### The Current Directory and Defined Path

It is necessary to declare a current directory before saving a file, loading a file, or running an M-file. By default, unless you edit the MATLAB shortcut, the current directory will be .../MATLAB/work. After you start MATLAB, change the current directory by either using the toolbar at the left-hand side of the screen, or entering the path in the bar at the top.

The current directory is the directory MATLAB will look in first for a function you try to call. Therefore if you have multiple folders and each of them has an M-file of the same name, there will not be a discrepancy if you set the current directory beforehand. The current directory is also the directory in which MATLAB will first look for a data file.

If you still want to call a function but it is not part of the current directory, you must define it using MATLAB's 'set path' utility. To access this utility, follow the path:

file > set path... > add folder...

You could also go to "add folder with subfolders...", if you're adding an entire group, as you would if you were installing a toolbox. Then look for and select the folder you want. If you forget to do this and attempt to access a file that is not part of your defined path list, you will get an 'undefined function' error.

### Saving Files

There are many ways to save to files in MATLAB.

• save - saves data to files, *.mat by default
• uisave - includes user interface
• hgsave - saves figures to files, *.fig by default
• diary [filename] - saves all the text input in the command window to a text file.

All of them use the syntax:

save filename.ext

or similar for the other functions. The files are saved in your current directory, as seen on the top of the window. By default the current directory is .../MATLAB/work.

Likewise, there are many ways to load files into the workspace. One way is to use the "file" menu. To open a .m file click "open", whereas to import data from a data file select "import data..." and follow the wizard's instructions.

An alternative way to load a saved .mat file (within a function, for example) is to type:

The file must be in a recognized directory (usually your current directory, but at least one for which the path has been set).

The data in the .mat file is stored with the same name as the variable originally had when it was saved. To get the name of this and all other environment variables, type "who".

To open an .m file, you can use file -> open, or type

>>open filename.ext

### File Naming Constraints

You can name files whatever you want (usually simpler is better though), with a few exceptions:

• MATLAB for Windows retains the file naming constraints set by DOS. The following characters cannot be used in filenames:
"  / : * < > | ?
• You're not allowed to use the name of a reserved word as the name of a file. For example, while.m is not a valid file name because while is one of MATLAB's reserved words.
• When you declare an m-file function, the m-file must be the same name as the function or MATLAB will not be able to run it. For example, if you declare a function called 'factorial':
function Y = factorial(X)
You must save it as "factorial.m" in order to use it. MATLAB will name it for you if you save it after typing the function declaration, but if you change the name of the function you must change the name of the file manually, and vice versa.

## Introduction

MATLAB is interesting in that it is dynamically compiled. In other words, when you're using it, you won't run all your code through a compiler, generate an executable, and then run the executable file to obtain a result. Instead, MATLAB simply goes line by line and performs the calculations without the need for an executable.

Partly because of this, it is possible to do calculations one line at a time at the command line using the same syntax as would be used in a file. It's even possible to write loops and branches at the command line if you want to. Of course this would often lead to a lot of wasted efforts, so doing anything beyond very simple calculations, testing to see if a certain function, syntax, etc. works, or calling a function you put into an .m file should be done within an .m file.

## Calculator

MATLAB, among other things, can perform the functions of a simple calculator from the command line. Let us try to solve a simple problem: Sam's car's odometer reading was 3215 when he last filled the fuel tank. Yesterday he checked his odometer and it read 3503. He filled the tank and noticed that it took 10 gallons to do that. If his car's gas tank holds 15.4 gallons, how long can he drive before he is going to run out of gas, assuming the gas mileage is the same as before?

First let us compute the distance Sam's car has travelled in between the two gas fillings

>> 3503-3215
ans =
288

Gas mileage of Sam's car is

>> 288/10
ans =
28.8

With this, he can drive

>> 28.8 * 15.4
ans =
443.5200

443.52 miles before he runs out of gas.

Let us do the same example, now by creating named variables

>> distance = 3503-3215
distance =
288
>> mileage = distance/10
mileage =
28.8000
>> projected_distance = mileage * 15.4
projected_distance =
443.5200

To prevent the result from printing out in the command window, use a semicolon after the statement. The result will be stored in memory. You can then access the variable by calling its name. Example:

>>projected_distance = mileage * 15.4;
>>
>>projected_distance
projected_distance =
443.5200

## Using the command line to call functions

The command line can be used to call any function that's in a defined path. To call a function, the following general syntax is used:

>> [Output1, Output2, ..] = functionname(input1, input2,..)

MATLAB will look for a file called functionname.m and will execute all of the code inside it until it either encounters an error or finishes the file. In the former case, it produces a noise and displays an error message in red. In the latter case, MATLAB will relinquish control to you, which you can see when the >> symbol is visible on the bottom of the workspace and the text next to "start" button on the bottom-left of the screen says "ready".

Use this in order to call homemade functions as well as those built into MATLAB. MATLAB has a large array of functions, and the help file as well as this wikibook are good places to look for help on what you need to provide as inputs and what you will get back.

Be careful; the syntax for functions and for indexing arrays is the same. To avoid confusion, just make sure you don't name a variable the same as any function. To ensure this, type the name of the variable you want to define in the command prompt. If it tells you:

Error using ==> (functionname)
Not enough input arguments.

then you'll have a conflict with an existing function. If it tells you:

??? Undefined function or variable '(functionname)'

you'll be OK.

## External Resources

ControlTheoryPro.com

# MATLAB File I/O: from the Command Line

## Generic Import

importdata examines the extension and loads the data depending on the extension.

uiimport opens a window to examine data.

## *.mat files

The quickest means of saving and retrieving data is through the binary .mat file format MATLAB provides. This is the native format for MATLAB.

• Note: This author has had some problems with certain classes not being saved correctly when saving data using version 7 for use in version 6. Most data items will work just fine. Of particular interest was an issue with State-Space objects that were saved using version 7 to a version 6 compatible file. When the file was opend in MATLAB version 6+ the State-Space objects did not load.Spradlig (talk) 04:52, 31 March 2008 (UTC).

### Saving Data

The save command is used to save workspace data to a file.

• Save all workspace data to the file mySave.mat in the current directory.
>> save('mySave.mat')
>> save(fullfile(pwd, 'mySave.mat'))
• Save just the variables myData1 and myData2 to mySave.mat.
>> save('mySave.mat', 'myData1', 'myData2')
• Save all myData variables to mySave.mat.
>> save('mySave.mat', 'myData*')
• Save all myData variables to a mySave.mat file compatible with version 6 of MATLAB.
>> save('mySave.mat', 'myData*', '-v6')
• Save all myData variables to an ASCII file.
>> save('mySave.txt', 'myData*', '-ASCII')
• Append new variables to the data file.
>> save('mySave.mat', 'newData*', '-append')

The load command is used to load data from a file into the current workspace.

• Load all variables from the file mySave.mat into the current workspace.
• Load just the variables myData1 and myData2.
• Get a cell array of variables in saved file.
>> whos('-file', 'mySave.mat')

Since analyzing data is one of the more common motivations for using input output I will start with reading and writing from a spreadsheet. I cover the command line first since it is often necessary to import the data while an m-function is being evaluated.

MATLAB makes it easy to read from an Excel spreadsheet. It has the built in command "xlsread". To use the xlsread function use the syntax:

This line of code reads filename.xls (from the current directory) and places it in an identical array inside MATLAB called g. You can then manipulate the array g any way you want. Make sure that the file you choose is in the same directory were you save your M-files (usually the work directory) otherwise you get an error. You can specify the path to a file but, this can get messy.

To write data to an .xls the procedure is very similar. The xlswrite command below creates a spreadsheet called filename.xls in the current directory from the variable g:

>> xlswrite('filename',g);

NOTE: if you are using MATLAB 6.5 there is no "xlswrite" command (that I'm aware of). There are several ways to write to a file. The simplest way I have found is

fid=fopen('newFile.xls', 'w');
fprintf(fid,'%6.3f %6.3f %10.3f\n', g);
fclose(fid);

You can substitute newFile.xls with .txt. Also, there might be some issues with formatting in Excel. The formatting issues can usually be handled inside Excel but if they can't you might have to play around with the fopen command parameters. This is pretty similar (if not the same) way you would write to a file in C.

## Text files I/O

This works only if the text is entirely numerical, without special formatting. Otherwise you get an 'unrecognized character' error.

The easiest way to write to a non-excel file, or using MATLAB 6.5 or less, is to use the same code as that for writing excel files but change the extension. Usually there are no formatting difficulties with plain text files.

For reading more general text files, MATLAB does not have a function to do it easily (unless you have excel), but you can read very general text files (with different delimiters for both cells and text within cells) using the "textread.m" function in the MATLAB file exchange (do a google search to find it). You can also try to use fscanf if the formatting is consistent enough (i.e. consistent numbers of spaces, no mixing of strings and numbers in columns, and so on).

# MATLAB File I/O: from the Graphical User Interface

MATLAB contains a nice GUI application that will guide you through importing data from any recognized data file (usually .mat, .txt, or .xls on a Windows system). To use it, go to file > import data, and select the file you want. Then, choose what column separators are present (by selecting the appropriate radio button). Finally, click "next".

MATLAB saves the variable under a name similar to that of the file, but with modifications to make it conform with MATLAB syntax. Spaces are omitted, plusses and minuses are turned into other characters. To see the name MATLAB generated (and probably change it) type "who" in the command prompt.

## External Resources

ControlTheoryPro.com

MatlabCodes.Webs.com

# Chapter 3: Data Storage and Manipulation

Data Types and Operations on Point Values

## Introduction

A large number of MATLAB's functions are operations on two types of numbers: rational numbers and boolean numbers.

Rational numbers are what we usually think of when we think of what a number is. 1, 3, and -4.5 are all rational numbers. MATLAB stores rational numbers as doubles by default, which is a measure of the number of decimal places that are stored in each variable and thus of how accurate the values are. Note that MATLAB represents irrational numbers such as pi with rational approximations, except when using the symbolic math toolbox. See that section for details.

Boolean numbers are either "TRUE" or "FALSE", represented in MATLAB by a 1 and a 0 respectively. Boolean variables in MATLAB are actually interchangable with doubles, in that boolean operators can be performed with arrays of doubles and vice versa. Any non-zero number in this case is considered "TRUE".

Most of the rational operators also work with complex numbers. Complex numbers; however, cannot be interchanged with boolean values like the real rationals can.

## Rational Operators on Single Values

MATLAB has all the standard rational operators. It is important to note, however, that Unless told otherwise, all rational operations are done on entire arrays, and use the matrix definitions. Thus, even though for now we're only talking about operations on a single value, when we get into arrays, it will be important to distinguish between matrix and componentwise multiplication, for example.

Add, Subtract, multiply, divide, exponent operators:

a = 1 + 2

%subtraction
b = 2 - 1

%matrix multiplication
c = a * b

%matrix division (pseudoinverse)
d = a / b

%exponentiation
e = a ^ b

The modulo function returns the remainder when the arguments are divided together, so a modulo b means the remainder when a is divided by b.

%modulo
remainder = mod(a,b)

All of these functions except for the modulus work for complex numbers as well.

## Relational Operators

Equality '==' returns the value "TRUE" (1) if both arguments are equal. This must not be confused with the assignment operator '=' which assigns a value to a variable.

>> %relational
>>a=5;b=5;
>>a==b
ans = 1
%Assignment
>>a=5;b=3;
>>a=b
a = 3

Note that in the first case, a value of 1 (true) is returned, however for the second case a gets assigned the value of b.

Greater than, less than and greater than or equal to, less than or equal to are given by >, <, >=, <= respectively. All of them return a value of true or false. Example:

>>a=3;b=5;
>>a<=b
ans = 1
>>b<a
ans = 0

## Boolean Operators on Single Values

The boolean operators are & (boolean AND) | (boolean OR) and ~ (boolean NOT /negation). A value of zero means false, any non-zero value (usually 1) is considered true.

Here's what they do:

>>%boolean AND
>> y = 1 & 0
y = 0
>> y = 1 & 1
y = 1
>>%boolean OR
>> y = 1 | 0
y = 1
>> y = 1 | 1
y = 1

The negation operation in MATLAB is given by the symbol ~, which turns any FALSE values into TRUE and vice versa:

>> c = (a == b)
c = 1
>> ~c
ans = 0

This is necessary because conditionals (IF/SWITCH/TRY) and loops (FOR/WHILE) always look for statements that are TRUE, so if you want it to do something only when the statement is FALSE you need to use the negation to change it into a true statement.

The NOT operator has precedence over the AND and OR operators in MATLAB unless the AND or OR statements are in parenthesis:

>> y = ~1 & 0
y = 0
>> y = ~(1&0)
y = 1

## Terminology

MATLAB refers to Booleans as "logicals" and does not use the word "Boolean" in code or documentation.

## Declaring Strings

Strings are declared using single quotes:

>> fstring = 'hello'
fstring =
hello

Including a single quote in a string is done this way:

>> fstring = ''''
fstring =
'
>> fstring = 'you''re'
fstring =
you're

## Strings as a Character Array

Strings in MATLAB are an array of characters. To see this, executing the following code:

>> fstring = 'hello';
>> class(fstring)
ans = char

Because strings are arrays, many array manipulation functions work including: size, transpose, and so on. Strings may be indexed to access specific elements.

Performing arithmetic operations on character arrays converts them into doubles.

>> fstring2 = 'world';
>> fstring + fstring2
ans = 223   212   222   216   211

These numbers are from the ASCII standard for each character in the array. These values are obtained using the double function to turn the array into an array of doubles.

>> double(fstring)
ans = 104   101   108   108   111

The 'char' function can turn an array of integer-valued doubles back into characters. Attempting to turn a decimal into a character causes MATLAB to round down:

>> char(104)
ans = h
>> char(104.6)
ans = h

## Special String Functions

Since MATLAB strings are character arrays, some special functions are available for comparing entire strings rather than just its components:

### deblank

deblank removes white spaces from the string.

### findstr

findstr(bigstring, smallstring) looks to see if a small string is contained in a bigger string, and if it is returns the index of where the smaller string starts. Otherwise it returns [].

### strrep

strrep(string1, replaced, replacement) replaces all instances of replaced in string1 with replacement

### strcmp

Strings, unlike rational arrays, do not compare correctly with the relational operator. To compare strings use the strcmp function as follows:

>> string1 = 'a';
>> strcmp(string1, 'a')
ans = 1
>> strcmp(string1, 'A')
ans = 0

Note that MATLAB strings are case sensitive so that 'a' and 'A' are not the same. In addition the strcmp function does not discard whitespace:

>> strcmp(string1, ' a')
ans = 0

The strings must be exactly the same in every respect.

If the inputs are numeric arrays then the strcmp function will return 0 even if the values are the same. Thus it's only useful for strings. Use the == operator for numeric values.

>> strcmp(1,1)
ans = 0.

## Displaying values of string variables

If all you want to do is display the value of a string, you can omit the semicolon as is standard in MATLAB.

If you want to display a string in the command window in combination with other text, one way is to use array notation combined with either the 'display' or the 'disp' function:

>> fstring = 'hello';
>> display( [ fstring 'world'] )
helloworld

MATLAB doesn't put the space in between the two strings. If you want one there you must put it in yourself.

This syntax is also used to concatenate two or more strings into one variable, which allows insertion of unusual characters into strings:

>> fstring = ['you' char(39) 're']
fstring = you're

Any other function that returns a string can also be used in the array.

You can also use the "strcat" function to concatenate strings, which does the same thing as above when you use two strings, but it is especially useful if you are using a cell array of strings because it lets you concatenate the same thing to all of the strings at once. Unfortunately you can't use it to add white space (strcat discards what MATLAB considers extraneous whitespace). Here's the syntax for this use.

>> strCell = {'A', 'B'};
>> strcat(strCell, '_');
ans =
A_
B_

Finally, although MATLAB doesn't have a printf function you can do essentially the same thing by using 1 as your file identifier in the fprintf function. The format identifiers are essentially the same as they are in C.

>> X = 9.2
>> fprintf(1, '%1.3f\n', X);
9.200

The "9.200" is printed to the screen. fprintf is nice compared to display because you don't have to call num2str on all of the numbers in a string - just use the appropriate format identifer in the place you want it.

>> X = 9.2
>> fprintf(1, 'The value of X is %1.3f meters per second \n', X);
The value of X is 9.200 meters per second

## Cell arrays of strings

In many applications (particularly those where you are parsing text files, reading excel sheets with text, etc.) you will encounter cell arrays of strings.

You can use the function "iscellstr" to tell if all of the elements in a given cell array are strings or not.

>> notStrCell = {'AA', []};
>> iscellstr(notStrCell)
ans = 0

This is useful since functions that work with cell arrays of strings will fail if provided with something that's not a cell array of strings. In particular, they all fail if any elements of the provided cell array are the empty array ( [] ) which is somewhat frustrating if the provided text file contains empty cells. You must catch this exception before calling cellstr manipulation functions.

Searching a cell array of strings can be done with the "strmatch", "strfind", and "regexp" functions. Strmatch looks for a string within a cell array of strings whose first characters exactly match the string you pass to it, and returns the index of all strings in the array for which it found a match. If you give it the 'exact' option, it will only return the indexes of elements that are exactly the same as what you passed. For example:

>> strCell = {'Aa', 'AA'};
>> strmatch('A', strCell);
ans = 1, 2
>> strmatch('A', strCell, 'exact');
ans = []
>> strmatch('Aa', strCell, 'exact');
ans = 1

Strfind looks for a specific string within a cell array of strings, but it tries to find it in any part of each string. For each element x of the given cell array of strings, it will return an empty array if there is no match found in x and the starting index (remember, strings are arrays of characters) of all matches in x if a match to the query is found.

>> strCell = {'Aa', 'AA'};
>> strfind(strCell, 'A');
ans = % answer is a cell array with two elements (same size as strCell):
1         % Index of the beginning of string "A" in the first cell
1  2      % Index of each instance of the beginning of string "A" in the second cell
>> strfind(strCell, 'a');
ans =
2

The "cellfun" / "isempty" combination is very useful for identifying cases where the string was or was not found. You can use the find function in combination with these two functions to return the index of all the cells in which the query string was found.

>> strCell = {'Aa', 'AA'};
>> idxCell = strfind(strCell, 'a');
>> isFound = ~cellfun('isempty', idxCell); % Returns "0" if idxCell is empty and a "1" otherwise
>> foundIdx = find(isFound)
foundIdx = 2

The strfind function also has some other options, such as the option to only return the index of the first or last match. See the documentation for details.

The regexp function works the same way as strfind but instead of looking for strings literally, it tries to find matches within the cell array of strings using regular expressions. Regular expressions are a powerful way to match patterns within strings (not just specific strings within strings). Entire books have been written about regular expressions, so they cannot be covered in as much detail here. However, some good resources online include regular-expresions.info and the MATLAB documentation for the matlab-specific syntax. Note that MATLAB implements some, but not all, of the extended regular expressions available in other languages such as Perl.

Unfortunately, MATLAB does not innately have functions to do common string operations in some other languages such as string splitting. However, it is quite possible to find many of these functions in a google search.

Portable functions are expressions defined once, then called whenever it is needed regardless of the platform. Portable functions include anonymous functions, and function handles. A third form of portable functions which is being phased out is inline functions.

## Anonymous Functions

Anonymous functions can be created from the command line without a script.

>> convert_min_to_s = @(t) t*60;
>> convert_min_to_s(4)
ans =
240

## Function Handles

Function handles are doubles serving as an abstract reference to the function. Handles allow an equation to be passed to another function for direct evaluation. Anonymous functions are useful for command-line evaluation or for multiple evaluations in the same m-file.

The ampersat returns the handle of a function either built into Matlab or defined in an M-file.

>> sum_by_a_different_name = @sum;
>> sum_by_a_different_name([3 3])
ans =
6
>> not_sum ([3 3])
??? Undefined function or method 'not_sum'
for input arguments of type 'double'.

## Function Handles in m-files

If you are not familiar with m-files, then skip this and come back.

A function handle passes an m-file function into another function. This of course lets you have more control over what's passed there, and makes your program more general as it lets you pass any m-file (as long as it meets other requirements like having the right number of input arguments and so on). The functionality is similar to that of function pointers in C++.

To pass an m-file to a function, you must first write the m-file, say something like this:

function xprime = f(t,x)
xprime = x;

Save it as myfunc.m. To pass this to another function, say an ODE integrator, use the @ symbol as follows:

>> ode45(@myfunc, [0:15], 1)

One advantage of using function handles over anonymous functions is that you can evaluate more than one equation in the m-file, thus allowing you to do things like solve systems of ODEs rather than only one. Anonymous functions limit you to one equation.

### How to write a function that accepts a function handle

Functions can accept function handles. To do this define them as variables in your header, and then call the handles as if they were functions:

function result = myfunc(func, a, b);
result = func(a, b);

[in a separate m-file]
sum = a+b;

The command you send to myfunc looks like this:

>> result = myfunc(@myadd, 1, 2);
result = 3

## Inline Functions

Inline functions are currently being phased out. Anonymous functions should be used instead. Inline functions are included here for information purposes.

>> convert_s_to_ms = inline('x*1000','x');
>> convert_s_to_ms(20)
ans =
20000

## Declaring a complex number in MATLAB

Complex numbers in MATLAB are doubles with a real part and an imaginary part. The imaginary part is declared by using the 'i' or 'j' character. For example, to declare a variable as '1 + i' just type:

>> compnum = 1 + i
compnum = 1.000 + 1.000i
>> compnum = 1 + j
compnum = 1.000 + 1.000i

Note that if you use j MATLAB still displays i on the screen.

Since i is used as the complex number indicator it is not recommended to use it as a variable, since it will assume it's a variable if given a choice.

>> i = 3; %bad idea
>> a = 1 + i
a = 4

However, since implicit multiplication is not normally allowed in MATLAB, it is still possible to declare a complex number like this:

>> i = 3;
>> a = 1i + 1
a = 1.000 + 1.000i

It's best still not to declare i as a variable, but if you already have a long program with i as a variable and need to use complex numbers this is probably the best way to get around it.

If you want to do arithmetic operations with complex numbers make sure you put the whole number in parenthesis, or else it likely will not give the intended results.

## Arithmetic operations that create complex numbers

There are several operations that create complex numbers in MATLAB. One of them is taking an even root of a negative number, by definition.

>> (-1)^0.5
ans = 0.000 + 1.000i
>> (-3)^0.25
ans = 0.9306 + 0.9306i

As a consequence of the Euler formula, taking the logarithm of a negative number also results in imaginary answers.

>> log(-1)
ans = 0 + 3.1416i

In addition, the roots of functions found with the 'roots' function (for polynomials) or some other rootfinding function will often return complex answers.

## MATLAB functions to manipulate complex values

First of all, it is helpful to tell whether a given matrix is real or complex when programming, since certain operations can only be done on real numbers. Since complex numbers don't have their own class, MATLAB comes with another function called 'isreal' to determine if a given matrix is real or not. It returns 0 if any of the inputs are complex.

>> A = [1 + i, 3];
>> isreal(A)
ans = 0
>> isreal(A(2))
ans = 1

Notice that it is possible to have real and complex numbers in the same array, since both are of class double. The function is set up this way so that you can use this as part of a conditional, so that a block only is executed if all elements of array A are real.

To extract just the real part of a complex variable use the 'real' function. To extract just the complex part use the 'imag' function.

>> real(A)
ans = 1    3
>> imag(A)
ans = 1    0

One thing you may need to do is perform an operation on the real values of an array but not the complex values. MATLAB does not have a function to directly do this, but the following pair of commands lets you put only the real values into another array:

>> RealIndex = (imag(A) == 0); %if imaginary part is zero then the number is real)
>> RealOnly = A(RealIndex)
RealOnly = 3

Arrays and Matrices

## Introduction to Arrays

An array is the most fundamental data type in MATLAB. In MATLAB, as in many traditional languages, arrays are a collection of several values of the same type. The string and number data type formerly presented are particular cases of arrays.

A matrix is an array with two dimensions. Most arrays have the same data type; however, a cell array is an array with varying data types. If no data type is specified for numbers, then the default data type is the equivalent to the double precision floating point in the C programming language on the same architecture. For example on x86 and powerpc a double has 64 bits.

The following list are pages involving work with MATLAB arrays:

## Declaring Arrays

### Row and Column Arrays

A row array is created using comma separated values inside brackets:

>> array = [0, 1, 4, 5]
array =
0     1     4     5

Sometimes commas are omitted for simple row arrays. Omitting commas is not recommended because in larger more complex arrays white-spaces can be ambiguous. Commas almost always indicate an array is horizontal.

A column array is created using semicolons to separate values:

>> column = [1; 2; 3]
column =
1
2
3

### Declaring multi-dimensional arrays

A two dimensional array (or a matrix) is declared with commas separating columns, and semicolons separating rows:

>> matrix = [1, 2, 3; 4, 5, 6]
matrix =
1     2     3
4     5     6

Simple matrix manipulation is the basis of many linear algebra computations. To use arrays of more than two dimensions, a matrix has to be extended using indexing.

When declaring arrays in MATLAB all rows and all columns need have same size. If not an error message will be generated:

>> matrix = [1, 2, 3; 4, 5]
??? Error using ==> vertcat
All rows in the bracketed expression must have the same
number of columns.

## Indexing Arrays

Arrays are indexed using integers. To return a single element in a simple array, use a single integer.

>> array = [0, 1, 4, 5];
>> array(3)
ans =
4

To return a single element in a two dimensional array one number as a row index and the second as a column index.

>> matrix = [1, 2, 3; 4, 5, 6];
>> matrix(2,2)
ans =
5

To return multiple elements in an array an array can be used as an index.

>> array = [0, 1, 4, 5];
>> array([1 3])
ans =
0    4

To return the last element of an array use (end).

>> array = [0, 1, 4, 5];
>> array(end)
ans =
5

A range of indexes can be returned using a colon(:)

>> array = [0, 1, 4, 5];
>> array(2:end)
ans =
1     4     5

## Properties of MATLAB arrays and matrices

Contrary to low level languages such as C, an array in MATLAB is a more high level type of data: it contains various information about its size, its data type, and so on.

>> array = [0,1,4,5];
>> length(array)
ans = 4
>> class(array)
ans = double

The number of rows and columns of the matrix can be known through the built-in size function. Following the standard mathematical convention, the first number is the number of rows and the second is the number of columns:

>> matrix = [1, 2, 3; 4, 5, 6];
>> size(matrix)
ans =
2     3

The goal of MATLAB arrays is to have a type similar to mathematical vectors and matrices. As such, row and column arrays are not equivalent. Mono-dimensional arrays are actually a special case of multi-dimensional arrays, and the 'size' function can be used for them as well.

>> size(array)
ans =
1     4

Row and column do not have the same size, so they are not equivalent:

>> size(column)
ans =
3     1
>> size(row)
ans =
1     3

## Why Use Arrays?

A major advantage of using arrays and matrices is that it lets you avoid using loops to perform the same operation on multiple elements of the array. For example, suppose you wanted to add 3 to each element of the array [1,2,3]. If MATLAB didn't use arrays you would have to do this using a FOR loop:

>> array = [1,2,3];
>> for ii = 1:3
array(ii) = array(ii) + 3;
>> end
>> array
array = [4,5,6]

Doing this is not efficient in MATLAB, and it will make your programs run very slowly. Instead, you can create another array of 3s and add the two arrays directly. MATLAB automatically separates the elements:

>> array = [1,2,3];
>> arrayofthrees = [3,3,3];
>> array = array + arrayofthrees
array = [4,5,6];

If all you are doing is adding a constant, you can also omit the declaration of 'arrayofthrees', as MATLAB will assume that the constant will be added to all elements of the array. This is very useful, for example if you use an array with variable size:

>> array = [1,2,3];
>> array + 3
ans = [4,5,6]

The same rule applies to scalar multiplication.

See Introduction to array operations for more information on the operations MATLAB can perform on arrays.

Arrays are a fundamental principle of MATLAB, and almost everything in MATLAB is done through a massive use of arrays. To have a deeper explanation of arrays and their operations, see Arrays and matrices.

## Introduction to array operations

As arrays are the basic data structure in MATLAB, it is important to understand how to use them effectively. See the previous section for that.

Arrays in MATLAB obey the same rule as their mathematical counterpart: by default, the matrix definitions of operations are used, unless a special operator called the dot operator is applied.

Because arrays operations are so similar to the equivalent mathematical operations, a basic knowledge of linear algebra is mandatory to use matlab effectively. However, we won't be as precise as in mathematics when using the terms vector and matrix. In MATLAB, both are arrays of doubles (thus being a matrix in the real mathematical meaning), and MATLAB considers vectors as a matrices with only one row or only one column. However, there are special functions just for vectors; see the vector module for an explanation of how to use these.

## Basics

### Accessing elements of a matrix

#### Using a Single Index

Now that you know how to define a simple array, you should know how to access its elements. Accessing the content of an array is done through the operator (), with the index inside the parenthesis; the indexing of the first element is 1:

>> a = [1, 2, 3];
>> a(1)

ans =

1
>> a(3)

ans =

3

Accessing an element outside the bounds will result in an error:

>> a(5)
???  Index exceeds matrix dimensions.

#### Using Multiple Indexes

To access a single matrix element, you can use the (i,j) subscript, where i is the index in the row, and j in the column:

>> a= [1, 2; 3, 4];
>> a(1, 2)

ans =

2

>> a(2, 1)

ans =

3

#### Using A Unique Index

You can also access a matrix element through a unique index; in this case, the order is column major, meaning you first go through all elements of the first column, then the 2d column, etc... The column major mode is the same as in Fortran, and the contrary of the order in the C language.

>> a = [1, 2, 3; 4, 5, 6];
>> a(3)

ans =

2

#### Using a Colon (:) for a Block Index

It is also possible to access blocks of matrices using the colon (:) operator. This operator is like a wildcard; it tells MATLAB that you want all elements of a given dimension or with indices between two given values. For example, say you want to access the entire first row of matrix a above, but not the second row. Then you can write:

>> a = [1, 2, 3; 4, 5, 6];
>> a(1,:) %row 1, every column
ans =
1     2     3

Now say you only want the first two elements in the first row. To do this, use the following syntax:

>> a = [1, 2, 3; 4, 5, 6];
>> a(1, 1:2)
ans =
1     2

The syntax a(:) changes a into a column vector (column major):

>> a = [1, 2, 3; 4, 5, 6]
>> a(:)
ans =
1
4
2
5
3
6

#### Using the end Operator

Finally, if you do not know the size of an array but wish to access all elements from a certain index until the end of the array, use the end operator, as in

>> a = [1, 2, 3; 4, 5, 6]
>> a(1, 2:end) %row 1, columns from 2 until end of the array
ans =
2     3

In addition to index addressing, you can also access only elements of an array that satisfy some logical criterion. For example, suppose a = [1.1, 2.1, 3.2, 4.5] and you only want the values between 2 and 4. Then you can achieve this in two ways. The first is to use the find function to find the indices of all numbers between 2 and 4 in the array, and then address the array with those indices:

>> a = [1.1, 2.1, 3.2, 4.5];
>> INDICES = find(a >= 2 & a <= 4);
>> a(INDICES)
ans =
2.1   3.2

This does not work in MATLAB 2006b.

The second method is to use logical addressing, which first changes a into a logical array, with value 1 if the logical expression is true and 0 if it is false. It then finds and returns all values in the a which are true. The syntax for this is as follows:

>> a = [1.1, 2.1, 3.2, 4.5];
>> a(a >= 2 & a <= 4)
ans =
2.1   3.2

## Basic operations

### Rational Operators on Arrays

The interesting part is of course applying some operations on those arrays. You can for example use the classic arithmetic operations + and - on any array in matlab: this results in the vector addition and subtraction as defined in classic vector vectors spaces ${\displaystyle \mathbb {R} ^{n}}$, which is simply the addition and subtraction elements wise:

>> [1, 2, 3] - [1, 2, 1]

ans =

0   0   2

#### Multiplication by a Scalar

The multiplication by a scalar also works as expected:

>> 2 * [1, 2, 3]

ans =

[2, 4, 6]

#### Multiplying and Dividing Arrays

Multiplication and division are more problematic: multiplying two vectors in ${\displaystyle \mathbb {R} ^{n}}$ does not make sense. It makes sense only in the matrix context. Using the symbol * in matlab computes the matrix product, which is only defined when the number of columns of the left operand matches the number of rows of the right operand:

>> a = [1, 2; 3, 4];
>> a * a

ans =
7    10
15    22
>> a = [1, 2, 3]; b = [1; 2; 3];
>> a * a
??? Error using ==> *
Inner matrix dimensions must agree.
>> a * b

ans =

14

Using the division symbol / has even more constraints, as it imposes the right operand to be invertible (see Wikipedia:Invertible matrix). For square matrices, ${\displaystyle a/b}$ is equivalent to ${\displaystyle a*b^{-1}}$. For example :

>> a = [1, 2; 3, 4]; b = [1, 2; 1, 2]
>> b / a

ans =

1     0
1     0
>> a / b
Warning: Matrix is singular to working precision.

ans =

Inf   Inf
Inf   Inf

#### Component-wise Operations

If you desire to multiply or divide two matrices or vectors component-wise, or to raise all components of one matrix to the same power, rather than using matrix definitions of these operators, you can use the dot (.) operator. The two matrices must have the same dimensions. For example, for multiplication,

>> a = [1, 2, 3];
>> b = [0, 1, 2];
>> a .* b

ans =

0    2    6

The other two componentwise operators are ./ and .^.

As matlab is a numerical computing language, you should keep in mind that a matrix which is theoretically invertible may lead to precision problems and thus giving imprecise results or even totally wrong results. The message above "matrix is singular to working precision" should appear in those cases, meaning the results cannot be trusted.

Non-square matrices can also be used as the right operand of /; in this case, it computes the pseudoinverse. This is especially useful in least square problems.

#### Transpose

A transpose of a matrix is taken using .'

>> array = [1,2;3,4]
array =
1     2
3     4
>> array.'
ans =
1     3
2     4

### Boolean Operators on Arrays

The same boolean operators that can be used for point values can also be used to compare arrays. To do this, MATLAB compares the elements componentwise and returns them in a logical array of the same size as the two arrays being compared. The two arrays must have the same size. For example,

>> A = [2,4], B = [1,5];
>> A < B

ans =
[0    1]

You must be careful when using comparisons between arrays as loop conditions, since they clearly do not return single values and therefore can cause ambiguous results. The loop condition should be reducable to a single boolean value, T or F, not an array. Two common ways of doing this are the "any" and the "all" functions. A function call any(array) will return true if array contains any nonzero values and false if all values are zero. It does the comparisons in one direction first then the other, so to reduce a matrix you must call the any function twice. The function all, similarly, returns true if and only if all elements in a given row or column are nonzero.

### Concatenating Arrays

Concatenating arrays involves sticking arrays together.

##### Horizontal Concatenating

Horizontal concatenation is done by treating an array as if it were a variable included in a row.

>> a = [1,2;3,4];
>> b = [5,6;7,8];
>> c = [a,b]
c =
1     2     5     6
3     4     7     8
##### Vertical Concatenating

Vertical concatenation is done by treating an array as if it were a variable included in a column.

>> a = [1,2;3,4];
>> b = [5,6;7,8];
>> c = [a;b]
c =
1     2
3     4
5     6
7     8

## Solving Linear Systems

To solve a linear system in the form Ax = b use the "\" operator.

Example:

>>A = [4 5 ; 2 8];
b = [23 28]';
x = A\b

x =

2
3

A vector in MATLAB is defined as an array which has only one dimension with a size greater than one. For example, the array [1,2,3] counts as a vector. There are several operations you can perform with vectors which don't make a lot of sense with other arrays such as matrices. However, since a vector is a special case of a matrix, any matrix functions can also be performed on vectors as well provided that the operation makes sense mathematically (for instance, you can matrix-multiply a vertical and a horizontal vector). This section focuses on the operations that can only be performed with vectors.

## Declaring a vector

Declare vectors as if they were normal arrays, all dimensions except for one must have length 1. It does not matter if the array is vertical or horizontal. For instance, both of the following are vectors:

>> Horiz = [1,2,3];
>> Vert = [4;5;6];

You can use the isvector function to determine in the midst of a program if a variable is a vector or not before attempting to use it for a vector operation. This is useful for error checking.

>> isvector(Horiz)
ans = 1
>> isvector(Vert)
ans = 1

Another way to create a vector is to assign a single row or column of a matrix to another variable:

>> A = [1,2,3;4,5,6];
>> Vec = A(1,:)
Vec = 1   2   3

This is a useful way to store multiple vectors and then extract them when you need to use them. For example, gradients can be stored in the form of the Jacobian (which is how the symbolic math toolbox will return the derivative of a multiple variable function) and extracted as needed to find the magnitude of the derivative of a specific function in a system.

### Declaring a vector with linear or logarithmic spacing

Suppose you wish to declare a vector which varies linearly between two endpoints. For example, the vector [1,2,3] varies linearly between 1 and 3, and the vector [1,1.1,1.2,1.3,...,2.9,3] also varies linearly between 1 and 3. To avoid having to type out all those terms, MATLAB comes with a convenient function called linspace to declare such vectors automatically:

>> LinVector = linspace(1,3,21)
LinVector = Columns 1 through 9
1.0000    1.1000    1.2000    1.3000    1.4000    1.5000    1.6000    1.7000    1.8000
Columns 10 through 18
1.9000    2.0000    2.1000    2.2000    2.3000    2.4000    2.5000    2.6000    2.7000
Columns 19 through 21
2.8000    2.9000    3.0000

Note that linspace produces a row vector, not a column vector. To get a column vector use the transpose operator (') on LinVector.

The third argument to the function is the total size of the vector you want, which will include the first two arguments as endpoints and n - 2 other points in between. If you omit the third argument, MATLAB assumes you want the array to have 100 elements.

If, instead, you want the spacing to be logarithmic, use the logspace function. This function, unlike the linspace function, does not find n - 2 points between the first two arguments a and b. Instead it finds n-2 points between 10^a and 10^b as follows:

>> LogVector = logspace(1,3,21)
LogVector = 1.0e+003 *
Columns 1 through 9
0.0100    0.0126    0.0158    0.0200    0.0251    0.0316    0.0398    0.0501    0.0631
Columns 10 through 18
0.0794    0.1000    0.1259    0.1585    0.1995    0.2512    0.3162    0.3981    0.5012
Columns 19 through 21
0.6310    0.7943    1.0000

Both of these functions are useful for generating points that you wish to evaluate another function at, for plotting purposes on rectangular and logarithmic axes respectively.

## Vector Magnitude

The magnitude of a vector can be found using the norm function:

>> Magnitude = norm(inputvector,2);

For example:

>> magHoriz = norm(Horiz)
magHoriz = 3.7417
>> magVert = norm(Vert)
magVert = 8.7750

The input vector can be either horizontal or vertical.

## Dot product

The dot product of two vectors of the same size (vertical or horizontal, it doesn't matter as long as the long axis is the same length) is found using the dot function as follows:

>> DP = dot(Horiz, Vert)
DP = 32

The dot product produces a scalar value, which can be used to find the angle if used in combination with the magnitudes of the two vectors as follows:

>> theta = acos(DP/(magHoriz*magVert));
>> theta = 0.2257

Note that this angle is in radians, not degrees.

## Cross Product

The cross product of two vectors of size 3 is computed using the 'cross' function:

>> CP = cross(Horiz, Vert)
CP = -3   6   -3

Note that the cross product is a vector. Analogous to the dot product, the angle between two vectors can also be found using the cross product's magnitude:

>> CPMag = norm(CP);
>> theta = asin(CPMag/(magHoriz*magVert))
theta = 0.2257

The cross product itself is always perpendicular to both of the two initial vectors. If the cross product is zero then the two original vectors were parallel to each other.

## Introduction to Structures

MATLAB provides a means for structure data elements. Structures are created and accessed in a manner familiar for those accustomed to programming in C.

MATLAB has multiple ways of defining and accessing structure fields. See Declaring Structures for more details.

Note: Structure field names must begin with a letter, and are case-sensitive. The rest of the name may contain letters, numerals, and underscore characters. Use the namelengthmax function to determine the maximum length of a field name.

## Declaring Structures

Structures can be declared using the struct command.

>> a = struct('b', 0, 'c', 'test')
a =
b: 0
c: 'test'

In MATLAB, variables do not require explicit declaration before their use. As a result structures can be declared with the '.' operator.

>> a.c = 'test'
a =
c: 'test'

Structures can be declared as needed and so can the fields.

## Arrays of Structures

Structures can also be arrays. Below is an example

>> a = struct('b', 0, 'c', 'test');            % Create structure
>> a(2).b = 1;                                 % Turn it into an array by creating another element
>> a(2).c = 'testing'
a =
1x2 struct array with fields:
b
c
>> a(1)                                        % Initial structure
ans =
b: 0
c: 'test'
>> a(2)                                        % The second element
ans =
b: 1
c: 'testing'

## Accessing Fields

When the field name is known the field value can be accessed directly.

>> a.c
ans =
test
ans =
testing

In some cases you may need to access the field dynamically which can be done as follows.

>> str = 'c';
>> a(1).(str)
ans =
test
>> a(1).c
ans =
test

## Accessing Array Elements

Any given element in a structure array can be accessed through an array index like this

>> a(1).c
ans =
test

To access all elements in a structure array use the syntax {structure.field}. In order to get all values in a vector or array use square brackets ([]) as seen below.

>> [a.('c')]
ans =
testtesting
>> [a.('b')]
ans =
0     1

Or you can put them all into a cell array (rather than concatenating them) like this:

>> {a.('c')}
ans = {'test', 'testing'}

## Assigning values to a field of each struct array element

Matlab provides tools to assign values to a field of each array element. Consider the following struct array:

foo = struct('field_a',{1,2,3,4}, 'field_b',{4,8,12,16})

The following command assigns the same value to the field_b field of each array element:

value = 1;
[foo.field_b] = deal(value)

To assign different values to each array element:

value = {4,8,12,16};
[foo.field_b] = value{:}

With Matlab, it's possible to extract a subarray from an array by using logical indexing. Consider the following struct array:

foo = struct('field_a',{1,2,3,4},'field_b',{4,8,12,16})

To obtain a subarray from foo where all foo.field_a values are equal to 2, a boolean array can be used to perform logical indexing. So, a boolean test that returns a boolean array for this purpose would be:

[foo.field_a] == 2

So, by using this boolean array to perform logical indexing, Matlab defines a struct array whose elements consist of those from foo whose field_a value is equal to 2 by doing:

foo([foo.field_a] == 2)

# Cell Array Introduction

Cell Arrays can contain differing information in every element. These types of arrays are useful when interacting with spreadsheet software.

## Creating Cell Arrays

Cell arrays follow the same conventions as regular arrays except instead of square brackets use curly brackets.

array = [1, 2, 3; 4, 5, 6];
cell_array = {1, 2, 3; 4, 5, 6};

Cell arrays have fewer limitations than regular arrays. The regular array can hold strings; however, the string in each element must be the same length. If one element in a regular array is a string then all elements must be a string. Cell arrays have neither of these limitations.

cell_array = {1, 2, 'a', 'abc'; rand(3, 2), magic(3), eye(3), 'junk'}
cell_array =
[         1]    [         2]    'a'             'abc'
[3x2 double]    [3x3 double]    [3x3 double]    'junk'

With fewer limitations for the content of a cell array comes complications. While cell arrays are a powerful tool, these arrays work differently because each element can be almost anything.

## Dynamic Resizing

Cell arrays can be dynamically resized, which is a key feature in more advanced data structures. For example, a queue data structure using the commands:

cell_array{end+1}='a';
cell_array{end+1}='b';

An element can be popped from the front of the queue using the commands:

cell_array(1)=[]; % remove first element - resize
cell_array(1)=[]; % remove first element - resize

## Uses

### GUI Tables

Cell arrays are used when displaying a table to a figure.

uitable('Data',{'hello',1;2,'there'})

## Converting to and from cell arrays

### Converting From a Numeric Array into a Cell Array

Use num2cell to convert from a numeric into a cell array.

>> cell_array = num2cell(numeric_array);

### Converting From a Cell Array into a Numeric Array

Use cell2mat to convert from a cell into a numeric array.

>> numeric_array = cell2mat(numeric_cell_array);