# MATLAB

*Table of Contents*

### Introduction

MATLAB can be used for a wide variety of tasks from simple math like a scientific calculator to machine learning. The name MATLAB is short for Matrix Laboratory and can be used while being dynamically typed. This document will cover some basics and provide links to additional resources to assist in gaining a deeper understanding of MATLAB.

### Accessing MATLAB

You can get access to MATLAB by downloading the program directly onto your local machine. All University of Waterloo students are eligible to download and install it onto their own computers. This link can provide more assistance on how to download MATLAB locally.

Alternatively, MATLAB can also be accessed by using a remote desktop connection to login into a UWaterloo machine virtually. This will require the additional use of a virtual private network (VPN). This link can provide more assistance on how to connect to a UWaterloo machine virtually.

### Basic Layout

When you first start MATLAB, it should appear like Figure 1. The three main panels that are open are:

Current Folder – On the left, provides access to your files.

Command Window – In the center, allows you to enter commands at the command line.

Workspace – On the right, lets you view the data and variables currently stored and their values.

If a MATLAB script or function is open, you may also see an Editor panel in the center above the Command Window as well. This as the name implies, allows you to create, edit and change user defined scripts and functions.

Figure 1. The default layout of MATLAB when first opened [1]. |
---|

### Basic Program

Within MATLAB there are a couple different ways to run code. You can either type all the lines of code into a MATLAB script or function, and then execute those scripts or functions. Or you can enter those codes directly into the command window in order to dynamically type the code up. Both ways are useful for certain applications. If certain code is going to have to be repeated over and over, it can be useful to encapsulate that within a script or function. This is so that the user would not be required to type out each line every time they wanted to execute those set of commands.

The syntax of the code remains the same whether it is being typed into the command line or stored as a script or function within MATLAB.

You can create a MATLAB script or function by simply clicking the New button on the top ribbon while under the Home section. When you do this, if the Editor panel was not previously open, it will open in the center of the screen. Both MATLAB scripts and functions have the file extension of “.m”. The following blocks of code are examples of simple scripts and functions in MATLAB.

**Note:** Everything that follows the % is considered to be a comment. The program does not execute any of those and are only there to improve the readability of the code.

% Wiki Example: Script % % Description: This program calculates the sin(x) from 0 to pi and displays % the results in an array clc % Command to clear the MATLAB screen x = [0 pi/3 pi/2 2*pi/3 pi] y = sin(x) y

function [y] = FunctionExample(x) % Wiki Example: Simple Function % % Description: Accepts input of x, plots sin(x) and returns the result of % sin(x) as variable y. y = sin(x); plot(x,y) end

The key difference between a MATLAB script and function is that a script simply contains a list of commands for MATLAB to execute. A function on the other hand uses it's own local variables and accepts input arguments. It can also return a value without creating all the variables used within the function itself in the workspace. The input and output parameters of a function are stated in it’s definition line (the beginning of the function). This also is what tells MATLAB that this file stores a function.

To execute either script or function, you simply type out their name within the Command Window (keeping in mind the name is case-sensitive). If it is a function that requires an input argument, they also needs to be provided in parenthesis.

### Variables and Data Types

MATLAB is dynamically typed, meaning the user does not need to declare the type of the variable, it is determined when the command is run [2]. Here are examples of declaring variables in MATLAB:

a = 12 %double b = 13.2 %float c = "charlie" %string d = false %logical

One key difference between other programming software and MATLAB is that everything within MATLAB is stored as matrices. This means that even if something is a string, MATLAB still considers it a 1-by-1 matrix. It just recognizes that the elements within that 1x1 matrix are of string class. Here are some examples:

a = 9 % 1-by-1 double b = [4 5 6 7] % 1-by-4 double c = 56 < 12 % 1-by-1 logical d = a + b % 1-by-1 double

The following are some of the different variable classes [3]:

Class name | Type | Intended Use |
---|---|---|

double, single | Floating-Point Numbers | Required for fractional numeric data |

int8. uint8 | Integers | Used for signed and unsigned whole numbers |

char, string | Characters and Strings | Data type for text |

logical | Boolean | Used in relational conditions or to test state |

### Matrices

As MATLAB deals extensively with matrices, it is important to know how to create and use matrices. The following code provides examples of creating matrices [4]:

a = [1 2 3 4] % Creates a 1x4 matrix, also called a row vector b = [1 3 5; 2 4 6; 7 8 10] % Creates a 3x3 matrix where rows are separated by semicolons % You can also create matrices by using a built in function such as ones, zeros, or rand c = zeros(5,1) % Creates a 5x1 matrix with all elements filled with the number zero d = ones(4,3,2) % Creates a 4x3x3 matrix with all elements filled with the number one e = rand(3) % Creates a 3x3 matrix with all elements filled with random numbers

It is also important to know how to manipulate these matrices. Here are some common operations [4]:

a = [1 3 5; 2 4 6; 7 8 10] b = a + 10 % Addition of 10 to each element of the matrix c = sin(a) % Computes the sin of each element of the matrix d = a' % Transposes a matrix e = a*inv(a) % Performs matrix multiplication with matrix and and its inverse % If you want to perform elementwise multiplication rather than matrix multiplication, use the .* operator f = a.*a % Elementwise multiplication of two matrices % The matrix operator for multiplication, division and power can all be done element-wise like the following g = a.^3 % Raises each element of the matrix to the third power % Concatenation can be used to join two appropriate matrices together h = [a,a] % Creates a 3x6 matrix by horizontally concatenating a with itself l = [a;a] % Creates a 6x3 matrix by vertically concatenating a with itself

The following is how you index into matrices and arrays [5]:

a = [16 5 9 4 2 11 7 14]; %Create a simple array x = a(3) % Extract the third element x = a([1 5 6]) % Extract the first, fifth, and sixth elements x = a(3:7) % Extract the third through the seventh elements x = a(end) % Extract the last element x = a(5:end) % Extract the fifth through the last elements x = a(2:end-1) % Extract the second through the next-to-last elements A = [1 2 3; 4 5 6; 7 8 9] %Create a simple 3x3 matrix X = A(2,3) % Extract the element in row 2, column 4 X = A(2:3, 1:2) % Extract the elements from row 2 to 3 and column 1 to 3 % A single : in subscript position is shorthand for 1:end X = A(3,:) % Extract third row X = A(:,end) % Extract last column

### Arithmetic Operators

Here are some basic arithmetic operators that are useful to know [6]:

a = [1 2 3; 4 5 6; 7 8 9] b = [1 2 3] x = a + a % Add numbers element-wise or append strings x = "Hello" + "World" x = a - a % Subtract, element-wise x = a .* a % Multiply, element-wise x = a * a % Matrix multiplication x = a ./ a % Divide, element-wise x = a/b % Solve systems of linear equations of xA = B for x x = a.^3 % Raise to the power, element-wise x = a^3 % Matrix to the power x = a.' % Transpose vector or matrix x = a' % Complex conjugate transpose

### Relational Operators

Relational operators result in either a true or false state. Here are some examples [7]:

45 == 59 % Equal to, example results in false 10 ~= 12 % Not equal to, example results in true 21 > 41 % Greater than, example results in false 15 >= 15 % Greater than or equal to, example results in true 69 < 17 % Less than, example results in false 75 <= 42 % Less than or equal to, example results in false

### Logical Operators

Logical operators are used when multiple relations have to be compared to one another. Here are some examples [7]:

% Logical AND operator, & % Results in true if both left and right expressions are true true & true % Results in true true & false % Results in false false & true % Results in false false & false % Results in false % Logical OR operator, | % Results in true if left or right expressions are true true | true % Results in true true | false % Results in true false | true % Results in true false | false % Results in false % Short-circuited logical AND operator % If expression on the right is false, second expression is not checked to save time false && true % Results in false % Short-circuited logical OR operator % If expression on the right is true, second expression is not checked to save time true || false % Results in true

### Conditional Statements

Conditional statements allow you to choose which block of code runs at runtime [8]. They are extremely useful when used within functions and scripts to change their outcome based on certain conditions. The simplest conditional statement is the "if" statement. For example:

% Generate a random integer x = randi(100, 1); % If the remainder of x/2 is equal to 0, display that x is even if rem(x,2) == 0 disp("The number " + x + " is even") end

As can be seen above, the if statement evaluates the logical expression next to it. If the expression results in the logical value of true, it will execute the code that it encompasses. Keep in mind that all the code it encompasses has to be indented and that their is the keyword "end" present after that block of code.

Two other optional keywords that can be used with the if statement are "elseif" and "else". These are useful when there may be more than on condition that you want to test for. It should be noted that these keyboards can only be used after the if statement. For example:

% Generate a random integer x = randi(100,1) % Categorize the number as either small, medium, or large if x <= 30 disp("The number " + x + " is small") elseif x <= 80 disp("The number " + x + " is medium" else disp("The number " + x + " is large") end

The order in which each statement occurs is very important here. If the first condition results in a true value, only the block of code encompassed by that condition will be executed. The latter conditions will not even be checked. Therefore, keeping in mind the order you place your conditions is very important. You can have multiple "elseif" conditions, each with code they encompass. In contrast, with such conditionals, there can only be one if statement and else statement. If none of the "if" and "elseif" conditions are met, the code encompassed by the "else" statement will be executed.

### Loop Control

Loop control is used to execute a block of code repeatedly [9]. The following are the two kinds of loops:

#### For Loops

For loop statements are used to loop for a specific amount of times. Within the statement an incrementing index variable is used to keep track of the iterations. Here's an example of a simple for loop:

x = ones(1,10); for n = 2:6 x(n) = 2 * x(n-1); end

The index variable in this case is n, and it iterates 5 times, going from 2 to 6. Every time it preforms the predetermined calculations.

#### While Loops

While loops continue to execute the code within the loop as long as the condition stays true. Here is a simple example for a while loop:

n = 1; nFactorial = 1; while nFactorial < 1000000 n = n + 1 nFactorial = nFactorial * n end

This while loop will continue to loop until it find that the result of the nFactorial is not less than 1,000,000. When it find that it's condition is no longer met, it will end the loop.

Notice how each loop requires the keyword, "end". The code that is executed by the loop is encompassed by it's loop statement and the keyword "end". It is also indented to improve readability.

There are also many times when you need to use a loop within a loop. These are called nested loops and each loop requires it's own "end" keyword.

Other keywords that you may find useful are "break" and "continue". If you want to exit your loop from within the loop itself, irrespective of the loop conditions, you can have the code execute the "break" statement. This will exit whichever loop is currently running. If the keyword "continue" is executed from within the loop, it will continue onto the next iteration of the loop.

It is also important to realize that it is possible to create infinite loops. These are loops that never end on their own and can cause your program to continue running for unreasonable amount of time. To stop execution of the loop, press Ctrl + C.

### Help Keyword

The "help" keyword can be an invaluable tool for beginners and experienced individuals alike. Entering this keyword followed by the function, method, class or toolbox into the Command Window will returns the help text associated with it [10]. This help text usually has information on what the function or method expects as inputs along with other useful information. It can save you the trouble of having to search up the particulars and is a good idea to know about. The following is an example of what can be entered into the Command Window and its resulting output:

help break % Output break Terminate execution of WHILE or FOR loop. break terminates the execution of FOR and WHILE loops. In nested loops, break exits from the innermost loop only. break is not defined outside of a FOR or WHILE loop. Use RETURN in this context instead.

### Additional Resources

There are plenty of additional resources available so that you can learn all you want about MATLAB. Below are links to MATLAB documentation that you may find helpful:

Guide to getting started with MATLAB

### References

[1] MathWorks. “Desktop Basics.” MathWorks.com. https://www.mathworks.com/help/matlab/learn_matlab/desktop.html

(accessed April. 10, 2021).

[2] Sedgewick and K. Wayne. “APPENDIX E: MATLAB.” Introcs.cs.princeton.edu. https://introcs.cs.princeton.edu/java/11matlab/#:~:text=Matlab%20is%20dynamically%20typed.,type%20is%20determined

%20at%20runtime.&text=Or%2C%20if%20you%20name%20a,making%20it%20impossible%20to%20call (accessed April 12, 2021).

[3] MathWorks. “Fundamental MATLAB Classes.” MathWorks.com. https://www.mathworks.com/help/matlab/matlab_prog/fundamental-matlab-classes.html (accessed April. 11, 2021).

[4] MathWorks. “Matrices and Arrays.” MathWorks.com. https://www.mathworks.com/help/matlab/learn_matlab/matrices-and-arrays.html (accessed April. 11, 2021).

[5] Eddins, L. Shure and MathWorks. “Matrix Indexing in MATLAB.” MathWorks.com. https://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html (accessed April. 15, 2021).

[6] MathWorks. “Arithmetic Operations.” MathWorks.com. https://www.mathworks.com/help/matlab/arithmetic-operators.html?s_tid=CRUX_lftnav (accessed April. 11, 2021).

[7] MathWorks. “MATLAB Operators and Special Characters.” MathWorks.com. https://www.mathworks.com/help/matlab/matlab_prog/matlab-operators-and-special-characters.html (accessed April. 11, 2021).

[8] MathWorks. “Conditional Statements.” MathWorks.com. https://www.mathworks.com/help/matlab/matlab_prog/conditional-statements.html (accessed April. 12, 2021).

[9] MathWorks. “Loop Control Statements.” MathWorks.com. https://www.mathworks.com/help/matlab/matlab_prog/loop-control-statements.html (accessed April. 12, 2021).

[10] MathWorks. “help.” MathWorks.com. https://www.mathworks.com/help/matlab/ref/help.html (accessed April. 15, 2021).

*Contributors: *

User | Last Update |
---|---|

Mayurakhi Khan | 1021 days ago |

d327pate@uwaterloo.ca | |

Former user (Deleted) |

*Faculty Advisor: Chris Rennick*