› Demo-MAT1: MATLAB-Tutorial
MATLAB is a commercial computing environment developed by MathWorks, targeted specifically at numerical computations and simulations, that uses a proprietary language, also called MATLAB. MATLAB offers functionality for creating and manipulating arrays and matrices, for plotting functions and data and for implementing mathematical algorithms that solve physical and engineering problems. This tutorial gives a brief introduction to the MATLAB language using as environment MATLAB 2020. Basic MATLAB syntax (variables, operators, input, output, arrays, matrices, functions, plotting) is illustrated using small examples that are saved as MATLAB scripts. All examples will also run in the open source software Octave.
A computing environment like MATLAB or Octave offers a broad support for solving mathematical problems analytically as well as numerically. MATLAB programs hide implementation details and much of the underlying complexity. Engineers can set up models and generate solutions even without understanding mathematical model or numerical method very well initially, so they can just focus on their physical problem. Since powerful solvers are available, the focus is shifted from solving a problem to modeling it correctly.
MATLAB has powerful support for solving numerical problems that model common engineering problems. For example, the Ordinary Differential Equation solvers (ode45, ode23) in MATLAB solve time-dependent problems with a variety of properties. The PDE (Partial Differential Equation) Toolbox provides functions for solving partial differential equations that model structural mechanics and heat transfer problems using finite element analysis. The functions are well-documented and there are many examples available.
Octave is a computing environment and scientific programming language very similar with MATLAB and the open source pendant of MATLAB. While the environment is not as sleek as MATLAB, it is free, has the same basic capabilities and is suited for learning MATLAB language basics.
The tutorial is structured in eight sections that explain usage of the MATLAB Integrated Development Environment (IDE) and the most important MATLAB commands:
MATLAB's Home-Tab is organized in four windows, that are used for developing and running scripts.
- Folder view: displays the folders that contain m-files. Here you create new folders and new scripts.
- Workspace: displays the variables and functions of the running scripts.
- Editor: displays the contents of the script files. The actual programming is done in the editor.
- Command Window: displays commands and the output of statements.
A MATLAB program can be created in different ways:
- Interactive mode:
MATLAB can be used in interactive mode, by entering commands directly in the command window. Output is also shown in the command window. Interactive mode is useful for tutorials and for testing small program parts.
Larger MATLAB programs are collections of MATLAB scripts stored in a common folder. The folder can be anywhere on your computer but must be added to the MATLAB path by using HOME > Set Path Menu.
- MATLAB LiveScript:
MATLAB LiveScripts are a special type of scripts with extended documentation features.
A MATLAB script is a text file with the file type *.m, that contains the statements of the program.
MATLAB script names may contain only letters, numbers and subscript.
Valid names are for example myscript1.m, myscript2.m, myfun1.m, myfun2.m.
MATLAB scripts are created using the commands in the EDITOR > FILE menu (New, Open, Save etc.) and are executed using the commands in the EDITOR > RUN-Menu (Run, Run and Advance, Run Section).
First Lines in MATLAB
MATLAB statements can be variable declarations/assignments, operations with variables, input- or output-instructions,
control flow statements or function calls, that perform specific tasks (plots, mathematical computations etc.).
MATLAB statements can be terminated with a semicolon or not. If terminated with a semicolon, a statement will not
generate any output in the command window.
Before starting to explore the MATLAB language, it is useful to learn some commands that are needed frequently to keep a clean and organized workspace and command window.
- clear -- Clears workspace variables. You can delete selected variables or all variables. Useful for example when you run multiple scripts that use the same variable names.
- clc -- Clears command window (instructions and output). Useful when you want to start over with a clean slate.
- format compact -- Compactifies the command window output.
- help -- If you type help folowed by the name of a command or function, the corresponding help page is displayed.
Example: Find out what the clc command does.
When typing "help clc" in the command window, the documentation for the clc command is shown as below.
Hello World-Program in MATLAB
A Hello-World-program is the smallest runnable program in a programming language and outputs the Text "Hello World" to default output (here: the command window). We do it first in interactive mode and then in a script.
In interactive mode, we use only the command window. Statements are entered next to the the command prompt (indicated by >>) and executed by pressing ENTER.
We type the statement text='Hello World' in the command window and then press ENTER. As shown in the picture below, the variable (here: text) and its content (here: Hello World) are shown as output in the command window. Next, we type the statement disp('Hello World') and press ENTER. Again, the string is displayed, but this time without the name of the variable.
In script mode, we first create a new script with the name "test_hello.m", then type the MATLAB statements below in the script file and save it, and finally execute the script by clicking the "RUN"-Button.
The MATLAB platform after creating, editing, saving and running the script looks as shown below.
The code starts in line 1 with a comment (indicated by "%"-symbol), that states the name of the script file. Note that the following lines are also commented.
In lines 2 and 3 we insert code for resetting / preparing workspace and command window.
In line 4 we create a new variable "text" and assign it the value 'Hello world'.
In line 5 we print the string 'Hello World' using disp().
% Script: test_hello.m
clear;clc; % Clear workspace and command window
format compact % Compactify command window output
text = 'Hello World'
Comments in MATLAB
Comments in MATLAB start with a "%"-symbol followed by text. Comments are used for documentation purpose, they are not executed by the system. Two percent-symbols "%%" mark a section. Sections can be executed separately using the RUN SECTION-Button.
%% Section 1
% Comment 1: This is the first comment for section 1.
text = 'Let''s start simple' % Here we assign a value to the variable named text
%% Section 2
% Comment 2: This is the first comment for section 2.
a = 10 % Here we assign a value to variable a
b = 20 % Here we assign a value to variable b
Variables and data types
Variables are named memory spaces that store the data of your program. MATLAB variables are declared by simply assigning a value to them. The data type (number, string, array etc.) is assigned automatically by MATLAB. For example, all numbers (integer, floating points) are stored internally as double precision floating point numbers. Knowing the data type is important, since the data type determines the set of operations that you can perform with your variables.
Example: Using variables
The example shows how to declare variables and perform operations on them. Note that the +-symbol denotes different operations: in line 3, the addition of numbers, in line 5, the concatenation of strings.
When running the script test_variables.m, output in command window is as shown.
- Line 2: Declare two variables a, b by assigning values to them. Since the declarations are terminated with semicolon, output of the variables to the command window is suppressed.
- Line 3: Add the two variables (actually, their values) and store the result in the variable sum.
- Line 4: Declare two string variables s1, s2.
- Line 5: Concatenate the strings to form a new string.
- Line 6: Replace the "+"-character with the string ' or '.
MATLAB supports different data types, that are represented by classes:
- Numerical data types: int, single, double
- Boolean data types: logical
- String data types: string, char
In order to find out the exact data type and size of your variables, use the commands whos, class. With whos, you can find out size and type of workspace objects. With class, you can find out the data type of a variable.
String variables in MATLAB can be either of class "string" or of class "character array". When you create a string using single quotes, it is stored as character array. When you create a string using double quotes, it is stored as a string. A character array is a sequence of characters, just as a numeric array is a sequence of numbers. String arrays provide a set of functions for working with text as data.
Input and Output
Data stored in variables can be viewed in the workspace or displayed in the command window.
Output to command window
There are three ways to output variable values to command window.
- Type the name of a variable in a new line, with no terminating semicolon. In an assignment statement, omit semicolon at the end of a statement. The content of the variable then is displayed in the command window.
- Use disp()-function. This function. takes as argument a variable / vector / matrix and displays it, omitting the name of the variable.
- Use fprintf()-function. This function builds a formatted output by using placeholders for the variables to be inserted. In our example, the value of variable a will be inserted in the place indicated by the first "%d", the value of variable b will be inserted in the place indicated by the second "%d" etc.
Example: Output to command window
In this example we calculate the sum of two variables and generate output in the command window.
When running the script test_output.m, output looks as displayed.
Input from command window
When presenting a MATLAB script to non-technical users, it may be helpful to let them enter configuration parameters as input from the command window or an input dialog. Input entered in the command window can be stored in variables using the input(prompt)-function.
An input dialog as shown below is created using the MATLAB-function inputdlg. We pass four arguments to the function:
- prompt -- the labels of the input fields
- dlgtitle -- the title of the dialog
- windowsize -- the size of the window
- definput -- specifies the default value for each edit field. The definput argument must contain the same number of elements as prompt.
The function returns an array of strings "answer", that contains the values entered in the edit fields.
Control flow statements are used to determine which block of code to execute at run time (conditional statements, if-else) or to execute a block of code repeatedly (while-loop, for-loop).
Conditional statements (if-else)
Conditional statements are used to control which of two or more statement blocks are executed depending on a condition. In MATLAB, as in most programming languages, they are implemented using the if-else-syntax.
Example: Show message according to the size of the number
In this example the user is asked to enter a number smaller that 100 and according to the size of the input a message is displayed. In line 5, the condition "a < 30" is evaluated: If true, the statement in line 5 is executed and the program flow continues in the first line after the if-else-statement.
A While loop repeats the statements in the loop while a condition is evaluated as true.
Example: Calculate sum of first n numbers: sum = 1+2+...+n
In this example, a counter variable i is initialized with 1. In line 3 the loop condition "i <= 5" is checked. If "true", the statements in line 4-6 are executed (print the value of i, add the value of i to the value of sum, increment the value of i) and then the loop condition is checked again and the loop is repeated.
A For loop repeats the statements in the loop a specified number of times.
Vectors are one-dimensional arrays that store information.
They can be stored in row or column format. For example, x = [1 4 9] will be a row vector, and x = [1; 4; 9] will be a column vector.
Vectors are created in different ways: by listing their elements explicitly in square brackets, using functions, or using for-loops.
Elements of a vector are accessed using an index that starts at 1. For example, to access element i in vector x, we write x(i).
Example: Create vector with 5 elements
We first create a row vector with 5 elements, display the second element of the vector, then the elements 2, 3 and 4 and change element 3 to be the sum of the first two elements.
Example: Find out size and length of vector
Using the whos command, we can see that the vector x is actually a matrix with 1 row and 5 columns, is of class double and uses 40 bytes of storage.
MATLAB supports vector operations of two kinds: mathematical operations according to the rules of
linear algebra (transposition, addition, multiplication) and array-type elementwise operations.
Elementwise operations are distinguished from vector operations by usage of the dot character (.).
x * y means matrix multiplication, and works only if x is a 1xn row vector and y is a nx1 column vector.
x .* y means elementwise multiplication and works only if x and y are both row (or column) vectors of same size.
Vector and elementwise operations are the same for addition and subtraction, so the operators .+ and .- are not used. Since vectors actually are a special type of matrix, these operations are the same as the described below for matrices.
Data of MATLAB programs are stored in one- and two-imensional arrays (e.g. vectors and matrices). A good understanding of matrices is important, since variables and vectors are actually a special case of matrices. Matrices are created in different ways: by enumerating their elements explicitly in square brackets, using functions, or using for-loops.
Create matrix using enumeration
When declaring a matrix by explicit enumeration, row elements are separated by a space and columns are separated by semicolon.
Create matrix using functions
Many mathematical problems require to use matrices initialized with specific values, such as the identity matrix. In MATLAB, the declaration of these matrices is done using MATLAB functions such as zeros(), ones() or eye().
Create matrix using for loops
The creation of a matrix using for loops is required when the size and even the element values change dynamically depending on some parameters. In this case, it is recommended to preallocate the maximal required memory using the zeros()-function.
Elements of a matrix are accessed using a row index and a column index that both start at 1. For example, to access element in row i and column j in a matrix A with m rows and n columns, we write A(i, j). Element with row-index 1 and column-index 1 is accessed with A(1, 1), etc.
Example: Create matrix by enumeration
In this example we declare a matrix with two rows and three columns, display it using disp, and find out type and size using whos. The whos-command shows that it is indeed a 2x3 matrix and uses up 48 bytes of memory.
Example: Create matrices using MATLAB functions
In this example we create three matrices: A1 is a matrix with m rows and n columns whose elements are initialized with zeros. A2 is a mxn matrix whose elements are all initialized with 1. I_n is the identity matrix with n rows and n columns, with ones on the diagonal and 0 on all other elements.
Example: Extract elements from a matrix
Accessing elements from a matrix is done by using indexing and slicing. In this example we first extract element with row-index 2 and column-index 3 and store in in a variable el23, then we extract the rows from 1 and 3 and all columns and store the result in a new matrix A1, finally we extract the rows from 2 to 3 and columns from 1 to 2 and store the result in a new matrix A2.
MATLAB supports matrix operations of two kinds: mathematical operations according to the rules of linear algebra (transposition, addition, multiplication) and array-type elementwise operations. Elementwise operations are distinguished from matrix operations by usage of the dot character (.): A * B means matrix multiplication, A .* B means elementwise multiplication. Since matrix and elementwise operations are the same for addition and subtraction, the operators .+ and .- are not used.
Example: Matrix operations
This example shows frequently used matrix operations: transposition, addition, multiplication and elementwise multiplication. The transposed of a matrix A is obtained by writing A', i.e. the matrix name followed by a quotation mark.
A function is a reusable piece of code that is executed only when called. It is defined once and can be called multiple times.
Functions may have parameters and also may return parameters.
The most common application is to use predefined MATLAB-functions such as plot (for plotting) or linspace for creating equidistant vectors,
or solvers such as ode45.
User-defined functions can be defined in multiple ways:
- Function is stored in a separate m-file.
- Function is stored inline in the script where it is called.
- Function is defined as an anonymous function.
(1) Function stored in a separate m-file
In most cases, it is recommended to put the code of a function in its own function script.
A function script is a MATLAB m-file that contains only the definition of a single function and cannot be executed as a "normal" script. Function and function script must have the same name, for example a function with name myfun1 must be stored in a function script with name myfun1.m.
By storing a function in its own script, the function can be used by any other script in the MATLAB path by calling it with specific arguments.
Defining a function
Functions begin with the keyword "function", followed by the statement
outputargs = function_name(inputargs)
and end with the keyword "end". The actual function statements that define the relationship between the input arguments and the output arguments are written in the function body between the first line and the last line.
In order to display the general syntax of a function definition and generate a template for a new function, we use the New > Function-Button in the EDITOR-Tab. This creates a new function script "untitled.m" for the function "untitled" with two generic input arguments and two generic output arguments. Starting with this template, we create our own functions by changing name, arguments and code as needed.
function [outputArg1,outputArg2] = untitled(inputArg1,inputArg2)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
outputArg1 = inputArg1;
outputArg2 = inputArg2;
Example: Define and call a function myfun1
In this example, we create a function myfun1 that takes as input an array-parameter x and calculates the function values y = x*exp(-x2). The code to the left shows the function definition in the function script. In the test script myscript1.m we first create an equidistant vector x, then calculate the y-values by calling the function myfun1 and finally create a plot of the so created x,y-values.
MATLAB's plot-function is used to create 2D-line plots of data given as (x,y)-values. The plot-function takes as input two vectors that must be of same size, plus a number of formatting options for specifying line type, color, width, title, legend, axis labes etc.
(2) Local functions: Function stored inline in main script
Functions that will be used only in one script can be stored as local functions inline in that script, and should be placed at the end of the script. Local functions are visible only in the script in which they have been defined and cannot be used in other functions. Why use local functions at all, since the primary goal of a function is to make it reusable? There are situations when you develop new solvers for numerical methods and program variants of the same function, so you need to use it only locally in a test setting and also want to reuse the function name.
Example: Define and plot two local functions
In this example, we create two functions myfun1 and myfun2 inline in the test script "test_inlinefunction.m". The test script "test_inlinefunction.m" must also start with the keyword "function", however, this function has no input and output parameter and simply indicates that the script will contain inline functions. Both functions myfun1 and myfun2 have as input parameter a vector x, and calculate the y-values for given mathematical functions.
(3) Anonymous functions
An anonymous function is a function that is not stored in a script file, instead it is associated with a variable of type function_handle.
Informally, it is an inline function that is written in just one line with the help of the @-symbol.
Anonymous functions are used for functions whose defining statement can be written in just one line.
General syntax is <function_name> = @ (<param_list>) ( <computation>).
Example: Use anonymous functions
In this example three mathematical functions are defined as anonymous functions.
- Line 1-3: Define function f(x) = sin(2πx) and then calculate the function values at points x = 1 and x = 2.
- Line 4-8: Define polynomial p(x) = 1 + 2x + x2 and then calculate the function values at the equidistant points x = [0, 0.5, 1.0, 1.5, 2.0]. Since in the definition of the polynomial the dot-operator is used, it is allowed to pass a vector as argument to the function.
- Line 8-11: Define a function of two variables u(x,y) = 25xy, where x and y are allowed to be vectors of same size. Then, create two vectors x, y using linspace and calculate the function values z for these vector arguments.
% Example 1: Sin-Function
f = @(x) sin(2*pi*x);
y1 = f(1); y2 = f(2);
% Example 2: Polynomial
p = @(x) (1 + 2.*x + x.^2);
x = 0:0.5:2; % x = [0, 0.5, 1.0, 1.5, 2.0]
y = p(x);
% Example 3: Function with two variables
u = @(x,y)(25.*x.*y);
x = linspace(0,1,10); y = linspace(0,2,10);
z = u(x, y);
Plotting in MATLAB
When solving a mathematical problem such as an ordinary or partial differential equation numerically, it is important to be able to visualize the solution and the intermediate steps quickly and effortlessly, as this helps the intuitive understanding of the physical problem. MATLAB has a number of functions for creating different types of 2D and 3D plots: plot, surf, mesh, contour, quiver etc., that make this an easy task.
Here we explore the plot-functionality more in detail. Firstly, all plots are organized in figure windows, that are created with the figure command. If the command figure is not specified, a figure is created by default. The figure-command allows to specify options for the creation of the figure window, such as position and title.
2D-Plots with plot
The simplest plot is a 2D-line-plot of a function y = f(x), using the function plot(). The plot-function has the general syntax plot(X,Y), that creates a 2D line plot of the data in Y versus the corresponding coordinate values in X. X and Y must be vectors or matrices with matching size. For example, in order to create a plot of y = f(x) = x^2 for the discrete values X = [1,2,3,4,5] and Y = [1,4,9,16,25], we write
Advanced usage of plot() enables to use other input parameters and and also plot options specified as name-value-pairs.
Example 1: 2D-Line-Plot
In the next example we explore some of the plot options and display the sin and cos-function on the same axis.
- Line 2: Create a discretization of the interval [-2*pi, 2*pi] using an equidistant vector with 51 data points.
- Line 3 and 4: Define the y-values for the functions to be plotted.
- Line 5: Create new figure with width 700, heigth 500 at position (50, 50).
- Line 6: Plot the sin-function given by the coordinate vectors x and y1.
- Line 7: hold on retains plots in the current axes so that new plots can be added
- Line 8: Plot the cos-function given by the coordinate vectors x and y2.
- Line 9-11: Specify a title, legend and labels for the axes.
In MATLAB, it is possible to display plots on the same figure but on different axes using the subplot-function. The command subplot(m, n, p) divides the current figure in a grid of plots as specified by its parameters: m rows, n columns and the next plot at position p.
Example 2: 2D-Plot using figure and subplots
Assume you need to plot the functions y1(x) = sin(x)*exp(x) and y2(x) = x*cos(x) on the same figure, so that the first plot is above the second plot. Then with the command subplot(2,1,p) you create a grid with 2 rows and 1 column, plus new axes at position p = 1,2, as in this example.
- Line 5: Create subplot for upper plot at position p = 1
- Line 6-9: Create plot that will be placed at subplot p = 1. We specifiy linewidth, color and marker edge color of the plot using name-value pairs. Code line 6 is split using ellipses (...).
- Line 10: Create subplot for lower plot at position p = 2
- Line 11-14: Create plot that will be placed at subplot p = 2.
3D-Plots with surf
For creating a 3D-surface-plot of a function z = u(x,y), the function surf() is used. The surf-function has the general syntax surf(X, Y, Z), that creates a 3D height plot of the data in Z versus the coordinate values in X and Y. X, Y and Z must be matrices with matching size. The two matrices X and Y for the grid are obtained from the coordinate vectors for the x and y axis using meshgrid. If x is a vector with m elements and n is a vector with n elements, meshgrid(x, y) creates two nxm matrices X and Y: X replicates x as row vector n times, and Y replicates y as column vector m times.
The next example shows the basic usage of meshgrid and surf and the involved matrices X, Y, Z.
Example 1: 3D-Plot with surf
In this example, we create a surface plot of z = u(x, y) = x^2 - y^2 for x- and y-coordinates given as vectors.
- Line 1-2: Create coordinate vectors x and y.
- Line 1-2: Coordinate vectors x and y are used as input to create the matrices X and Y with meshgrid().
- Line 4: Calculate 3x4 matrix Z containing the function values.
- Line 5: Plot surface using surf.
The output in the command window is as shown:
Output X, Y from meshgrid: X = 1 2 3 4 1 2 3 4 1 2 3 4 Y = 0 0 0 0 0.5000 0.5000 0.5000 0.5000 1.0000 1.0000 1.0000 1.0000 Function values Z: Z = 1.0000 4.0000 9.0000 16.0000 0.7500 3.7500 8.7500 15.7500 0 3.0000 8.0000 15.0000
Example 2: 3D-Plot with surf
We plot the same function u(x,y) = x^2-y^2 over a rectangular area [a, b] x [c, d] and enhance the plot with details: title, axis labels, colorbar. We also show the contours and gradient vector field using the functions contour and quiver. The gradient of a function u(x,y) at a point is the directional derivative of the function; the gradient at all points of the domain defines a vector field that can be plotted using the quiver-function.
- Line 1: Define u as anonymous function.
- Line 2-3: Define rectangle [a, b] x [c, d] and number of data points nx= 10 and ny = 20 for the discretization.
- Line 4: Create evenly spaced x and y-coordinate vectors.
- Line 5: Generate the grid matrices X, Y from the evenly space x- and y-coordinates.
- Line 6: Calculate matrix Z containing the function values.
- Line 7: Calculate the gradient [px, py] of the function
- Line 9-13: Create surface plot of the function u.
- Line 14-20:Create 2D-plot of function with contour lines and gradient vector field.
Authors, Tools & References
Prof. Dr. Eva Maria Kiss
- MATLAB Help: https://de.mathworks.com/help/matlab/
- MATLAB Language Fundamentals: https://de.mathworks.com/help/matlab/language-fundamentals.html
- Octave Software:https://www.gnu.org/software/octave/
- Octave Manual:https://octave.org/doc/v6.1.0/