MATLAB Programming/Print Version

MATLAB Programming

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/MATLAB_Programming

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

Fundamentals of MATLAB

Main screen of MATLAB

When the MATLAB is opened for the first time after installing, you will see the MATLAB main display shown as followed (Note that the version is R2020a, which other versions may look more or less similar):

The main screen of MATLAB will consists of the following (in order from top to bottom):

• Search Bar - Can search the documentations online for any commands / functions / class
• Menu Bar - The shortcut keys on top of the window to access commonly used features such as creating new script, running scripts or launching SIMULINK
• Home Tab - Commonly used features/functions are grouped here
• Plots Tab - The plot charts is shown here. Basic charts (without additional toolbox are shown as follows):
Line Plots, Bar Plots, Scatter Plots, Pie Chart, Histogram, Polar Plots, Geographic Plots, Contour Plots,3D Surface, Vector Field and Analytic Plots
• Apps Tab - The additional installed toolbox with related functionality are shown here
• Current Folder Panel — The created files are accessed at this panel
• Command Window Panel — All of the workings are done at this panel, enter commands at the command line, indicated by the prompt (>>).
• Workspace Panel — Explore data that you had created or import the data from files at this panel

Hello World

All programming languages are introduced by the most famous computer program on the planet, "Hello World !", so let's begin with that.

In the center, you can see a window labelled as "Command Window". The cursor should be already flickering there; all you now have to do is to write as followed:

disp('Hello world')

and press the return key. The output will be shown just below the command as

Hello World !

Note: To pass the argument string in single quotes (not double), but why so? Because we might need to use double quotes inside the string and that would be interpreted as the end of the string argument. Having said this, it is assured that double quotes work inside the string, however escape sequences may have to be used to get the string right.

Start afresh

In MATLAB , once you are started working with a lot of mathematical formulas for one project , you will need to start afresh for your new project.

To do this, just type as follows:
clear
clc
close all

What does this three lines do ?

clear - This command will removes all stored variables from the workspace.

clc - This command will clear the command window and homes the cursor.

close all - This command will closes all the open figure windows.

[1]

Fundamentals of MATLAB/Basic MATLAB commands

Basic MATLAB command

During start to use the program, you may see "double greater than" symbols aka >> on the top left of command window.
You can start to type simple or complex mathematic equation to your liking.

Some of the examples are as follows:

>> 6+3 - 4/2

ans =
7

>> sind(30)

ans =
0.5000


or you may even assign a value to a variable / perform simple algebra equations

>> x = 200 % assigning value 200 to variable x

x =
200

>> y = 120 % assigning value 120 to variable y

y =
120

>> p = x-y % make a simple subtraction equation where the x is subtract y equals to p

p =
80


Basic Commands

These commands listed below are the commands that you usually will encounter when using MATLAB

clc - Clear command window.
clear - Remove all variable values from workspace
disp - Display the values inside of the variable / matrix
help - Display tooltip help text inside the Command Window. The help displays the help for the functionality specified by NAME, such as a function, operator symbol, method, class, or toolbox.

Hello World

For the beginner just starting into MATLAB programming, a tutorial is available to write Hello World.
Once Hello World, which is the simplest of programs, works the beginner can move on to explore the MATLAB workspace available for developing or running Matlab code.

Using the workspace the beginner can then learn to manipulate basic MATLAB Variables.

For convenience Matlab allows the workspace to be saved and loaded using *.mat files.

Examples of MATLAB Command

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.

Examples

MATLAB can perform the functions of a simple calculator from the command line. We go thru some of the common Maths problem in the real life.

Here are few of mathematics problem that are demonstrated to be solved in MATLAB:

Painting Coverages

A house painter usually uses 10L of white paint to cover 120 square meter on average for single layer of coating.

Calculate how many 10L paint cans that house painter needed to buy to paint a room with size of 13m X 9m with height 5m from floor to ceiling.

Also the room have 2 windows with size of 1.5m*0.75m and 2m*1.25m and a door with size of 1.2m*3m
>> room_area=13*9*5 %calculating the overall area of wall for the room

room_area =
585

>> window_area=(1.*0.75)+(2*1.25)

window_area =
3.2500

>> door_area=1.2*3

door_area =
3.6000

>> paint_area=room_area-window_area-door_area

paint_area =
578.1500

>>%amount of paint can needed
paint_area / 120

ans =
4.8179
%house painter needed equaivalent of 5 tin cans to paint the room


Earth to Sun Distance

Distances from sun to earth is equivalent to 150 million km (150,000,000 km)

If human launched a advance rocket capable of achieving constant speed of 7km/s (ignore all of the air frictions, gravitational pull) , how many year(s) does the rocket to reach the sun from earth ?
>> distance = 150000000

distance =
150000000

>> speed = 7

speed =
7

>> time = distance / speed

time =
2.1429e+07

>> time_to_reach_sun=time/(3600*24*365) % 3600= 1 hour =3600secs, 1 day = 24hour, 1 year=365days(discounting leap years)

time_to_reach_sun =
0.6795


Dice Roll for board games

You invite some friends come over to play a board game but somehow the dice that should be comes with board game is missing. Create a MATLAB programs to throw two dices (with 6 faces)

You need to use randi command to generate random numbers. More command can be learnt here: MATLAB Programming/Fundamentals of MATLAB/MATLAB operator
>> diceroll = randi(6) + randi(6) % press up button to recall last command and press Enter

diceroll =
9

>> diceroll = randi(6) + randi(6)

diceroll =
6

>> diceroll = randi(6) + randi(6)

diceroll =
9

>> diceroll = randi(6) + randi(6)

diceroll =
11

>> diceroll = randi(6) + randi(6)

diceroll =
5

>> diceroll = randi(6) + randi(6)

diceroll =
12


File Name Types

There are many types of files that are used in MATLAB. These are some of the few of commonly used files used for MATLAB.

.m

It consists a MATLAB script. This is a platform-independent file, so you can use the same scripts on whatever operating system (Windows, Linux,Mac) you’re working on at any time.

This file also allows you to create a script on one OS and share it with others, even when they use a different OS than you do. MATLAB script files are always written using the MATLAB language.

.mat

To save this file, click the "Save Workspace" and to load the data click "Load Data"

.slx

Simulink is an add-on product for MATLAB that provides a block diagram environment for performing simulations.

.fig

Provides access to any plots or other graphics you create. Keep in mind that the file contains all the information required to reconstruct the chart, but does not contain the graphic of chart itself.

This approach means that the chart's plot is accessible on any OS that MATLAB supports.

.mlapp

A MATLAB application created using the MATLAB App Designer.

MATLAB application lets you share your code in a packaged form (like executable files) with other people, and you can create one without having much of programming experience

Fundamentals of MATLAB/MATLAB operator

MATLAB Operator

MATLAB have a few operator types to manipulate shown below
Note: Variables a and b below represents number

Arithmetic Operations

Arithmetic Operator is used as mathematical operator that manipulates the number according to the formula requirement. The result is shown as numbers.

 Addition a + b Subtraction a - b Multiplication a * b Forward division a / b Backward division a \ b Exponentiation a ^ b Assignment a = b

Relational Operations

Relational Operator is used to check if numbers are having any significant relationship with one or another. The results is usually is shown TRUE or FALSE.

 Equal To a == b Not Equal To a ~= b Greater than a > b Greater or equal to a >= b Lesser than a < b Lesser or equal to a <= b

Logical Operations

Logical Operator is used to check if number fulfills the logical conditions, the result is usually shown TRUE or FALSE.

 Logical AND a && b Logical OR a || b Logical NOT a ~ b

Elementary Mathematics Constants and Functions

Besides mathematical formula, there are a few mathematical constant and function that you can use to make your works in Matlab easier. More information about the functions used can be found here:Mathematical_symbols

 pi Returns value of 3.1416 (Note: Ratio of a circle's circumference to its diameter) sqrt(a) Returns square root of a exp(1) Returns value of 2.7183 This is exponential function (Note: it is inverse of natural log, try log(exp(1) and see the result) log(a) This logarithm operator is to find natural number log of a number log10(a) This base10 log operator is common logarithm for base 10 mod(a,b) or rem(a,b) This modulo operator returns the remainder after a is divided by b. : (Colon) Generate a sequence round(a,b) This rounding operator round up to the number to the nearest digit "a" by the significant digit "b" b > 0: round to a digits to the right of the decimal point. b = 0: round to the nearest integer. b < 0: round to a digits to the left of the decimal point. primes(a) Returns a list of prime numbers less than or equal to number a gcd(a,b) Returns the greatest common divisors of the number of a and b. lcm(a,b) Returns the least common multiples of the number of a and b.

Trigonometry Operations

Trigonometry Triangles

The trigonometry formula are given as followed:
Sin α - a / h
Cos α - b / c
Tan α - a / b

 sin(α) This sine operator returns sine value of argument in radians sind(α) This sine operator returns sine value of argument in degree cos(α) This sine operator returns cosine value of argument in radians cosd(α) This sine operator returns sine value of argument in degree tan(α) This sine operator returns tangent value of argument in radians tand(α) This sine operator returns tangent value of argument in degree deg2rad(α) Convert angle from degrees to radian rad2deg(α) Convert angle from radians to degrees (Note: Try to convert the pi from radian to degrees)

Matrix Operations

 [ ] Container for matrix , Matrix row separator ; Matrix column separator

Others

 randi Random integer

Comment lines begin with the character '%', and anything after a '%' character is ignored by the interpreter. The % character itself only tells the interpreter to ignore the remainder of the same line.

In the MATLAB Editor, commented areas are printed in green by default, so they should be easy to identify. There are two useful keyboard shortcuts for adding and removing chunks of comments. Select the code you wish to comment or uncomment, and then press Ctrl-R (-/ for Mac) to place one '%' symbol at the beginning of each line and Ctrl-T (-T for Mac) to do the opposite.

MATLAB also supports multi-line comments, akin to /* ... */ in languages like C or C++, via the %{ and %} delimiters. But there is a small and important difference. In MATLAB it is not allowed that the lines starting with %{ or %} contains any other text (except white spaces). Otherwise it would not work. E.g.

%{ for i = 1:10
disp(i)
end %}


gives an error, but

%{
for i = 1:10
disp(i)
end
%}


works just fine.

Common uses

Comments are useful for explaining what function a certain piece of code performs especially if the code relies on implicit or subtle assumptions or otherwise perform subtle actions. Doing this is a good idea both for yourself and for others who try to read your code. For example,

% Calculate average velocity, assuming acceleration is constant
% and a frictionless environment.
force = mass * acceleration


It is common and highly recommended to include as the first lines of text a block of comments explaining what an M file does and how to use it. MATLAB will output the comments leading up to the function definition or the first block of comments inside a function definition when you type:

>> help functionname


All of MATLAB's own functions written in MATLAB are documented this way as well.

Comments can also be used to identify authors, references, licenses, and so on. Such text is often found at the end of an M file though also can be found at the beginning. Finally, comments can be used to aid in debugging, as explained in Debugging M Files.

Boolean and Rational

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.

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

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 component-wise multiplication, for example: Add, Subtract, Multiply, Divide, Exponent operators.

 %addition
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 =
logical
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


[2]

Strings

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


Concatenate Strings

In MATLAB , multiple strings can be concatenated (linked together as a chain) using square brackets.
<concatstring>=[<str1>,<str2>,<str3>,...];

Here are the random greeting message that are using this concatenate functions.
>> subject='The quick brown fox ' %sentence beginning

subject =
'The quick brown fox '

>> verb = 'jumps over '

verb =
'jumps over '

>> object='the lazy dog'

object =
'the lazy dog'

>> phrase=[subject,verb,object]

phrase =
'The quick brown fox jumps over the lazy dog'


Inputting strings

To let user input , we can use input functions
>> name=input('Enter your names: ','s')

name =
'Matlab_User'


String manipulations

Count the repeating words

Tounge twister of wood chuck
Consider the following tounge-twister

How much wood would a woodchuck chuck

if a woodchuck could chuck wood?

He would chuck, he would, as much as he could,

and chuck as much wood as a woodchuck would

if a woodchuck could chuck wood.

We would like to know how many times of the word wood appeared in that tounge twister. We can use the count function.
>>%Declare woodchuck twister as an characther vectors
>> twister = 'How much wood would a woodchuck chuck if a woodchuck could chuck wood? He would chuck, he would, as much as he could, and chuck as much wood as a woodchuck would if a woodchuck could chuck wood.'

twister =
'How much wood would a woodchuck chuck if a woodchuck could chuck wood? He would chuck, he would, as much as he could, and chuck as much wood as a woodchuck would if a woodchuck could chuck wood.'

>> count(twister,"wood")

ans =
8


Note that the function count are counting occurrences of pattern in strings .

Therefore, it will counting the word "wood" inside the word "woodchuck"

Now, we have have another examples to count the word " the" of the famous proverbs of-all-time

The quick brown fox jumps over the lazy dog

phrase = 'The quick brown fox jumps over the lazy dog'
%count function is case-sensitive by default . It did not count The with capital 'T'
>> count(phrase,'the')

ans =
1

%need to use IgnoreCase to turn off the case-sensitive words
>> count(phrase,'the','IgnoreCase',true)

ans =
2


Finding lengths of string

At times, you might be needing to find the length of words in a sentence, here is the length(string') functions comes to the rescue.
>> length(phrase)

ans =
43

As we can see in next section, it can be seen that there are exactly 43 characters inside the string.

Extracting words from Strings

To extracting certain words in the string, need to stringName(indexnumberfirst:indexnumberlast) .

We using the same example phrase as above.

Note that even empty space is consider as a string.

 Index Number 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 String T h e q u i c k b r o w n f o x j u m p s o vv e r t h e l a z y d o g

Based on this example, if we wanted to extract the word brown fox and lazy dog,

we can see that each word is represented by index number (11:19) and index number (36:43) respectively. In MATLAB , we can type following commands:
>> phrase(11:19)

ans =
'brown fox'

>> phrase(36:43)

ans =
'lazy dog'


Lowercase and Uppercase of Strings

For the string manipulations such as converting the strings to upper and lower cases, we can use lower and upper functions. This will make the strings all in lowercase and uppercase characthers respectively.
>>  upper(phrase)
>> %Convert the string to uppercase
ans =
'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG'

>> lower(phrase)
>> %Convert the string to lowercase
ans =
'the quick brown fox jumps over the lazy dog'


Reverse Strings

To reverse the string , we can use reverse / flip function. This will make the string reverse from the last index number to first index number and vice versa.
>> reverse(phrase)

ans =
'god yzal eht revo spmuj xof nworb kciuq ehT'


Replace Characters in Strings

To replace certain words in the strings, we can use replace functions

The syntax of replace functions are as followed: replace(stringName,oldword,newword)
>>% We don't want brown fox, we want to change to orange fox
>> replace(phrase,'brown','orange')

ans =
'The quick orange fox jumps over the lazy dog'

There are at times, you might want to replace multiple words in one go , therefore we need to declare the multiple strings in vector. But before that make sure, the order/sequences for old and new words are in correct order.
>>%declare vector where the old words are going to be replaced
>> old={'fox','dog'}

old =
1×2 cell array
{'fox'}    {'dog'}

>>%declare vector where the new words are going to do the replaing
>> new={'cheetah','sloth'}

new =
1×2 cell array
{'cheetah'}    {'sloth'}

>> % Replace old words (fox) and (dog) into (cheetah) and (sloth) . Make sure sequence is in correct order
>> replace(phrase,old,new)

ans =
'The quick brown cheetah jumps over the lazy sloth'


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.


num2str

Convert numbers to character . This functions is useful when you want to use function disp values to limit the display of decimal point.

>>%Limit the display of pi value to 9 decimal points
>> num2str(pi,'%1.9f')

ans =
'3.141592654'


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.

Complex Numbers

Complex Numbers

Complex numbers are also used in MATLAB.
It consists of two parts, one is real number and one is imaginary number. It is in the form of ${\displaystyle z=a+bi}$ or ${\displaystyle z=a+bj}$.
i or j returns the basic imaginary unit. i or j is equivalent to square root of -1 where the formula is ( ${\displaystyle i/j={\sqrt {-1}}}$ ).
Note: The symbol i and j are interchangeable for one to another, as MATLAB just convert j into i, if equations is using two different notations as shown below.

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 as following:

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

>>%Note:If you use j MATLAB still displays i on the screen
>> compnum = 1 + j
compnum = 1.000 + 1.000i


Note 1: Even if you use j to indicate complex number , MATLAB will still displays i on the screen.

Note 2: Since i is used as the complex number indicator it is not recommended to use it as a variable, since it will assume i is a variable.

 >> i = 1; %bad practise to use i as variable
>> a = 1 + i
a = 2


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 complex 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.

Complex functions

However, the best practice to declare a complex number is by using function complex.

>>%Best practise to declare complex number in MATLAB
>> complex(2,6)

ans =
2.0000 + 6.0000i


If you want to declare just the imaginary number, just use the square root of negative numbers, such as followed.

>> sqrt(-49)

ans =
0.0000 + 7.0000i


To declare multiple complex numbers , create two row vectors with real numbers and another with imaginary numbers. Combine both of them using complex functions

>> %create a vector consiots of real number
>> RE = [1,2,3]

RE =
1     2     3

>> %create a vector consiots of imaginary number
>> IM = [4,5,6]

IM =
4     5     6
>> %create 3 complex number
>> complex(RE,IM)

ans =
1.0000 + 4.0000i   2.0000 + 5.0000i   3.0000 + 6.0000i


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.

Manipulate complex numbers

Finding real and imaginary number

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=[complex(2,3),complex(4,0)]

A =
2.0000 + 3.0000i   4.0000 + 0.0000i

>> %returns 1 if complex number does not have an imaginary part and 0 if otherwise.
>> %A denotes the whole vectors
>> isreal(A)

ans =
logical
0
>> %A(2) denotes second complex number in the vector (4+0i)
>> isreal(A(2))

ans =
logical
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.

>>%Extract real number from the complex number vector A
>> real(A)

ans =
2     4

>>%Extract imaginary number from the complex number vector A
>> imag(A)

ans =
3     0


Complex conjugate

Complex conjugate picture
To find complex conjugate , we can use conj function. If complex number, Z is ${\displaystyle a+bi}$ , then the conjugate, Ẑ is ${\displaystyle a-bi}$
>> conj(A)

ans =
2.0000 - 3.0000i   4.0000 + 0.0000i


Phase Angle

To find phase angle , we can use the phase angle in the radian for each element of a complex numbers
>> angle(A)

ans =
0.9828         0


[3]

Vector and Matrices

What is scalar,vector and matrix ?

Scalar

Scalars are the physical quantities that are described by magnitude only. In other words, scalars are those quantities that are represented just by their numerical value, such as 3, -5, 0.368, etc.

Vector

A vector is an array of numbers or a list of scalar values in one dimensional array of numbers (can be in a row or column).

This example vector A below is row vector

${\displaystyle \mathbf {A} ={\begin{bmatrix}5&8&6\\\end{bmatrix}}.}$

This example vector B below is column vector

${\displaystyle \mathbf {B} ={\begin{bmatrix}7\\3\\2\end{bmatrix}}.}$

Matrix

A matrix is an ordered rectangular array arrangement of numbers. They are stored as two-dimensional arrays in MATLAB.
A matrix having m rows and n columns is called a matrix of order m × n or simply m × n matrix.
It can be represented by one or more rows (i) AND one or more columns (j).

Back in Introduction chapter , MATLAB was originally designed to carry out operations with matrices, and received the name of MATrix LABoratory that subsequently was reduced to MATLAB.

It is possible to find applications of matrices not only in the mathematics areas, but also in a great deal of applications in engineering, in physics, in finance, in accounting, in chemistry and in biology, perhaps more.

There are many types of matrices with followings as shown

 Rectangular Matrix (Where no. of row and column are unequal) Square Matrix (Where no. of row and column are same) Row Matrix (Matrix with one row , aka row vector) Column Matrix (Matrix with one column , aka column vector) Diagonal Matrix (Square Matrix with non-diagonal elements equal to zero ) ${\displaystyle \mathbf {\begin{bmatrix}9&5\\2&7\\8&3\end{bmatrix}} .}$ ${\displaystyle \mathbf {\begin{bmatrix}4&9&2\\3&5&7\\8&1&6\end{bmatrix}} }$ ${\displaystyle \mathbf {\begin{bmatrix}1&4&5\\\end{bmatrix}} }$ ${\displaystyle \mathbf {\begin{bmatrix}7\\9\\1\end{bmatrix}} }$ ${\displaystyle \mathbf {\begin{bmatrix}8&0&0\\0&7&0\\0&0&5\end{bmatrix}} }$

Scalar in MATLAB

Scalar in MATLAB looks like assigning a variable to a number such as followed:

 a = 6


Vectors in MATLAB

You can type following in MATLAB

For row vector , just type comma "," to separate each number

  >> VR = [6,2,5]
VR =
6     2     5


For column vector , just type semicolon ";" to separate each number

  >> VC = [9;1;6]
VC =
9
1
6


Matrix in MATLAB

In MATLAB, to create matrix (or matrices), there is 3 important operator to be used

(a) Bracket "[" "]" as container for the matrix
(b) Comma , as matrix row separator
(c) Semicolon ; as matrix column separator

For example, we are creating 4X3 matrix in MATLAB using following commands.

>> M = [4,8,9,6;9,6,9,6;3,6,9,6]

M =
4     8     9     6
9     6     9     6
3     6     9     6


Vector and Matrices/Special Matrices

Special Matrices

Matrix of ones

We can create matrix consists using the functions ones with m numbers of rows and n numbers of columns

>> ones(3,3)

ans =
1     1     1
1     1     1
1     1     1


Matrix of zeroes

We can create matrix consists using the functions zeros with m numbers of rows and n numbers of columns

>> zeros(3,3)

ans =
0     0     0
0     0     0
0     0     0


Identity Matrices

An identity matrix is a square matrix in which each of the elements of its diagonal is a 1 and each of the other elements is a 0. An identity matrix is used for following purposes:
(a) To verify whether any two given matrices are inverses of each other.
A and B in examples below are inverse to one another

  >> A=[3,-2;-1,1]
A =
3    -2
-1     1

>> B=[1,2;1,3]
B =
1     2
1     3

>> A*B
ans =
1     0
0     1


(b) To find the inverse of a matrix
Note 1: Not every inverse matrix can use have identity matrix
Note 2: Command "eye(n)" can be used to create identity matrix in a flash, n is the size of matrix

>> A=[3,2;4,3]
A =
3     2
4     3

>> eye(2)
ans =
1     0
0     1

>> eye(2)/A
ans =
3    -2
-4     3


(c) To find the eigenvalues and eigenvectors.
Eigenvalue is defined as a scalar associated with a given linear transformation of a vector space and having the property that there is some non-zero vector which when multiplied by the scalar is equal to the vector obtained by letting the transformation operate on the vector.

Let say we have a matrix A as followed:

${\displaystyle \mathbf {A} ={\begin{bmatrix}1&4\\3&2\\\end{bmatrix}}.}$

To find lambda, we need to know the equation for finding eigenvalue with following formula :
${\displaystyle |A-\lambda I|=0}$
But MATLAB provided a simple way to find eigenvalue using command "eig"

>> A=[1,4;3,2]
A =
1     4
3     2

>> lambda = eig(A)
lambda =
-2
5


Magic Square Matrices

A magic square is basically where the sum of the elements in each column and the sum of the elements in each row are the same and there are no repeating numbers. We can create a magic square use this command M=magic(n). The order n must be a scalar greater than or equal to 3 in order to create a valid magic square.

For more info, can refer to this well written Wikibooks on this topic: Puzzles/Luoshu Squares

For example , we can create a magic square with matrices 5 by 5

  >> % creating 5X5 matrix magic square
>> c = magic(5)
c =
17    24     1     8    15
23     5     7    14    16
4     6    13    20    22
10    12    19    21     3
11    18    25     2     9


Vector and Matrices/Operations on Matrices

Basic Matrix Operation

We can add and subtract the matrices if both of them are of same number of rows and columns.

Examples as follows:

  >> a = [7,9,4;6,2,5]
a =
7     9     4
6     2     5

>> b=[2,0,1;4,7,3]
b =
2     0     1
4     7     3

>> % Addition of a and b matrices
a+b
ans =
9     9     5
10     9     8

>> % Subtraction of a and b matrices
a-b
ans =
5     9     3
2    -5     2


Matrix multiplication

For matrix multiplications, there are 2 ways to do multiplications.

Matrix multiplication

(i) Matrix multiplications (using symbol * or mtimes)

Requirements is that the number of columns in the first matrix must be same as the number of rows in the second matrix.

As examples shown on the right , matrix A have 3 X 2 and matrix B have 2 X3

Therefore , 2 X 3 <-> 3 X 2 , hence, it fulfils the requirements above.

Also, take note that the resulting matrix sizes is based on number of rows of first matrix with number of columns in second matrix.

Matrix multiplication step by step
>> A=[4,2,4;8,3,1]

A =
4     2     4
8     3     1

>> B=[3,5;2,8;7,9]

B =
3     5
2     8
7     9

>> mtimes(A,B)

ans =
44    72
37    73

>> A*B

ans =

44    72
37    73

Following examples shows what if the incorrect matrix dimension matches.

As shown, the matrix C have 5X4 and matrix D have 3X2

5X 4 <-> 3X2, therefore it cannot fulfill the conditions and unable to solve it.
>> %Demonstrations what if matrices dimensions are incorrect
>> C=randi(10,5,4)

C =

2    10    10     3
2    10     4     5
3     5     2     1
5     5     8     2
1     4     4    10

>> D=randi(10,3,2)

D =

10     3
6     4
1     9

>> mtimes(C,D)
Error using  *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first
matrix matches the number of rows in the second matrix. To perform elementwise
multiplication, use '.*'.

(ii) Dot product (Note: Only can be used if both matrices are same sizes) Taking examples above, it doesn't solve the equations as both matrix A and B above are not same size
>> A.*B % want to show dot product unable to solve this multiplication issues
Matrix dimensions must agree.


Creating Random Integer Matrix

To generate random integer matrix, can type the following randi(IMAX,M,N)
Note: IMAX is the maximum integer (starting from 1) and M*N matrix

Examples as followed:

>> randi(50,3,4)

ans =
9    14    42    48
36     3    35     2
2     5    16    22


Transpose

Using the matrices above, we can transpose the matrices. Transpose matrices usually just switch the row to column and columns into rows. The picture shown just demonstrate the transpose operation. One of the application of transpose the matrix is to crytography.

Matrix transpose

There are two ways to go about it. One is add ' to the end of the matrix that are going to be transpose or function transpose.

Back to the magic square example above, we are going to transpose it. We can see , it is transpose along the diagonal line looks like this : \

  >> % transpose matrix c to d
>> d = c'
d =
17    23     4    10    11
24     5     6    12    18
1     7    13    19    25
8    14    20    21     2
15    16    22     3     9


Determinant

The determinant of matrix is a special number that is defined only for square matrices.
A determinant is used to find the solution of a system of linear equations and determine the inverse of a matrix.

Determinant of 2X2 matrix : ${\displaystyle \mathbf {A} ={\begin{bmatrix}a&b\\c&d\\\end{bmatrix}}*|A|=ad-bc}$

Determinant of 3X3 matrix : ${\displaystyle \mathbf {A} ={\begin{bmatrix}a&b&c\\d&e&f\\g&h&i\end{bmatrix}}*|A|=a(ei-fh)-b(di-fg)+c(dh-eg)}$

>> A=[6,1,1;4,-2,5;2,8,7]

A =
6     1     1
4    -2     5
2     8     7

>> det(A)
ans =
-306.0000


Inverse

Inverse of matrix is reciprocal matrix where the formula is denoted by ${\displaystyle {A}^{-1}={\frac {1}{|A|}}adjA}$

Note: Not all matrix have inverse, if their determinant is equal to zero.

>>%matrix inversion using manual method

>> M=[2,-1,3;-5,3,1;-3,2,3]

M =

2    -1     3
-5     3     1
-3     2     3

>> %First we find the matrix determinant
>> DM = det(M)

DM =
-1.0000

>>%Since determinant IS NOT equal to 0, we can find the matrix inverses

AM =
7.0000    9.0000  -10.0000
12.0000   15.0000  -17.0000
-1.0000   -1.0000    1.0000

>> (1/DM)*AM

ans =
-7.0000   -9.0000   10.0000
-12.0000  -15.0000   17.0000
1.0000    1.0000   -1.0000

%shortcut using function inv which should be same as manual calculation above
>> inv(M)

ans =
-7.0000   -9.0000   10.0000
-12.0000  -15.0000   17.0000
1.0000    1.0000   -1.0000


There are many applications of matrix such as:
Crytography : where it is used to encrypt message codes. Matrices are used by programmers to code or encrypt letters. A message is made up of a series of binary numbers that are solved using coding theory for communication. As a result, the concept of matrices is used to solve such equations.
In physics, the Inverse matrix is used to explore electrical circuits, quantum mechanics, and optics. These matrices are crucial in the measuring of battery power outputs and the conversion of electrical energy into other useable energy by resistors. When applying Kirchhoff’s laws of voltage and current to solve problems, the inverse matrices are extremely significant.

Vector and Matrices/Operations on Vectors

Operation on Vectors

Constructing Vectors

If a vector's elements is following the sequential additions, we can just use parentheses with the following:

${\displaystyle Vector=(first_{n}umber_{i}n_{t}he_{m}atrix:incremental_{v}alue:last_{n}umber_{i}n_{t}he_{v}ector)}$
As for example, if we want to have a vector starting with number 1 and ends with number 19 with the incremental values of 3, we can type commands shown below

>> V = (1:3:19)

V =
1     4     7    10    13    16    19


Accessing Vector

To access the values in vector , you just need to specify the vector and the array index, from 1 to n .

Using example of vector V above, we access single elements of vector V in third elements which we type commands as followed:

>> V(3)

ans =
7


We can access multiple elements by typing the start index and the end index For example, we need to access element no 3 up to element no 6, we type as followed:

>> V(3:6)

ans =
7    10    13    16


Finding Length

We can also use length function to knows what is the length of the vector ,for example we can know what is the length of V. There are 7 elements in vector V, therefore the answer should be 7

>> length(V)

ans =
7


Sum Vector

We can find the sums of vector using sum function, it get this values by adding all of the numbers inside vector together: For example, 1+4+7+10+13+16+19

>> sum(V)

ans =
70


Finding Max and Min

Respectively we can know which is the biggest and smallest number in a vector which we can use by using min and max functions

>> min(V)

ans =
1

>> max(V)

ans =
19


Finding Mean

The mean function is to find the center/middle value inside the vector

>> mean(V)

ans =
10


Finding Average

The average function is to find the average of the vector

>> average(V)

ans =
10

>> % Another way of finding average
>> sum(V)/length(V)

ans =
10


Finding Standard Deviation

To find standard deviation , std function is needed
The standard deviation is a measure of the amount of variation or dispersion of a set of values. A low standard deviation indicates that the values tend to be close to the mean (also called the expected value) of the set, while a high standard deviation indicates that the values are spread out over a wider range.

>> std(V)

ans =
6.4807


Random Permutation

There are two different ways to create random permutations for vector

a. randperm(N) returns a vector containing a random permutation of the integers 1:N.

>> P=randperm(7)

ans =
1     6     2     3     4     5     7


b. randperm(N,K) returns a row vector containing K unique integers selected randomly from 1:N

>>>> P=randperm(7,5)

P =
5     1     6     2     3


Sorting Vector

You may want to sort the vectors, you can do this MATLAB.

If the vectors are to be sorted in descending manner, use this example as followed. Note, we use the random permutation example b above.

>> % using argument 'descend' to sort from big to small number
>> S=sort(P,'descend')

S =
6     5     3     2     1

>> % using argument 'asscend' to sort from  small to big number
>> S=sort(P,'ascend')

S =
1     2     3     5     6


Calculating dot products

To find dot product,you can use the dot functions

NOTE: The two vectors must have the same length. The answer will usually in the forms of scalar .

The dot product of vector are calculated as followed

${\displaystyle A=[A1,A2,A3,...,An]}$

${\displaystyle B=[B1,B2,B3,...,Bn]}$

${\displaystyle A.B=A1.B1+A2.B2+A3.B3+...+An.Bn}$

>> % creating row vector A and B
>> A = [3 ,7 , 2]

A =
3     7     2

>> B = [1,2,5]

B =
1     2     5

>> dot(A,B)

ans =
27


Calculating cross products

To find cross product,you can use the cross functions NOTE: The two vectors must have the same length of 3. The answer will usually in the forms of vector 3 .

TODO: Search a picture that can illustrate the cross product well.

>> cross(A,B)

ans =
31   -13    -1


Calculating commonly used values in vector

To find the most duplicated values in the vector, we can use the mode functions.
>>%create vectors with random numbers
>> A=randi(50,1,10)

A =
18    42    30    28    46    15    38    38    20    29

>> mode(A)

ans =
38
>>%38 appear twice in that vector


Vector and Matrices/Sparse Matrices

A Sparse Matrix is a matrix that mostly contains zeros. In MATLAB, sparse matrices contrast regular ones in the way they are stored, such that memory is used more efficiently for matrices that are sparse.

A regular matrix can be converted to a sparse matrix using

  >> S = sparse(A);   % Create sparse representation of A


Sparse matrices are very common in engineering purposes. This is useful for manipulation as most of the matrix has a value of 0.

Arrays

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.

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

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

Basic vector operations

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.

Vectoring Mathematics

MATLAB is a vector programming language. The most efficient use of MATLAB will involve taking advantage of the built-in capabilities for manipulating data instead of using constructs such as loops.

Basic Math

Most arithmetic operators will work as expected on vectors:

>> a = [2 43 943 78];
>> 5 * a
ans =
10         215        4715         390
>> a / 2
ans =
1.0000   21.5000  471.5000   39.0000
>> 0.2 + a
ans =
2.2000   43.2000  943.2000   78.2000


Likewise, all of these operations can be done with matrices for the expected results.

Most MATLAB functions, such as sin or log, will return a vector or matrix of the same dimensions as its input. So to compute the sine of all the integers between 0 and 10, it suffices to run

>> sin(0:10)


and the returned vector will contains ten values.

Per Element Operations

Operators such as the carrot (^) or multiplication between vectors may not work as expected because MATLAB sees vectors the same as any other matrix, and so performs matrix power and matrix multiplication. All operators can be prefixed by a . to make it explicit that an operation should be performed on each element of the matrix. For example, to compute the differences of the sine and cosine function squared for all integers between 1 and 4, one can use:

>> (sin(1:4) - cos(1:4)).^2
ans =
0.0907    1.7568    1.2794    0.0106


as opposed to

>> (sin(1:4) - cos(1:4))^2
??? Error using ==> mpower
Matrix must be square.


which results from MATLAB's attempt to square a 1x4 vector using matrix multiplication.

Using .* or ./ allows one to divide each element of a matrix or vector by the elements of another matrix or vector. To do this, both vectors must be of the same size.

Converting Loops to Vector-based mathematics

Since MATLAB is a vector language, an artificial algorithm such as

x = [];
v = [5,2,4,6];
for i=1:4
x(i) = v(i) * ((i+32)/2 - sin(pi/2*i));
if(x(i) < 0)
x(i) = x(i) + 3;
end
end


can be done far more efficiently in MATLAB by working with vectors instead of loops:

i = 1:4;
v = [5,2,4,6];
x = v .* ((i+32)/2 - sin(pi/2*i));
x(x<0) = x(x<0) + 3;


Internally, MATLAB is of course looping through the vectors, but it is at a lower level then possible in the MATLAB programming language.

Arrays/Struct Arrays

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);