MATLAB Examples

Welcome to this MATLAB Video tutorial. If you have never used MATLAB before, this demonstration will get you started and show you where to go to next to learn more.

Every variable in MATLAB® is an array that can hold many numbers. When you want to access selected elements of an array, use indexing.

Three-dimensional plots typically display a surface defined by a function in two variables, z = f(x,y) .

You can display multiple plots in different subregions of the same window using the subplot function.

MATLAB is an abbreviation for "matrix laboratory." While other programming languages mostly work with numbers one at a time, MATLAB® is designed to operate primarily on whole matrices and

MATLAB® provides a large number of functions that perform computational tasks. Functions are equivalent to subroutines or methods in other programming languages.

To create two-dimensional line plots, use the plot function. For example, plot the value of the sine function from 0 to 2\pi :

When you are working with text, enclose sequences of characters in single quotes. You can assign text to a variable.

Some basic examples on how to use mutliple input set functions:

Example spreadsheet from a brain imaging study

The test along with its experimental results is described in:

This video tutorial will show you how to link plots to their data sources providing a live view of a variable and how to carry out data brushing, letting you select and manipulate data

Test for the good size of a matrix containing floats

This example was authored by the MathWorks community.

Place the UserDefinedConstants directory on your MATLAB search path

This function clears all empty variables from the current workspace.

This function sorts input matrix A and corresponding matrices using sortrows. Output matrices are sorted such that the first output is a sorted version of A, and all other outputs are sorted

Test for the presence of a string in a list of possible values

Test to have one integer

Format. The user can specify any number of digits to be carried, while doing a variety of different numerical computations on these numbers. Not all MATLAB operators are defined, as my main

Flip multiple matrices along specified dimensions.

Add the cell of names to a string

Test to have one double

In this case, yes, we know exactly the final size of the array. This example is merely a time test, plus it shows that growdata produces the correct size result.

Create handles to local functions. If a function returns handles to local functions, you can call the local functions outside of the main function. This approach allows you to have multiple,

Typically, you can import tables using the readtable function. However, sometimes importing tabular data requires additional control over the import process. For example, you might want

MATLAB® considers function handles that you construct from the same named function to be equal. The isequal function returns a value of true when comparing these types of handles.

These examples show several ways to pass data from a cell array to a MATLAB® function that does not recognize cell arrays as inputs.

Techniques for accessing data in arrays stored within cells of cell arrays.

Analyze bicycle traffic patterns from sensor data using the timetable data container to organize and preprocess time-stamped data. The data come from sensors on Broadway Street in

Perform calculations on tables.

All the scripts provided are used in Partial Differential Equation Methods for Image Inpainting (Carola-Bibiane Schoenlieb, Cambridge University Press, 2015):

The convhull and convhulln functions take a set of points and output the indices of the points that lie on the boundary of the convex hull. The point index-based representation of the convex

F. Moisy, 9 july 2008. University Paris Sud.

(c) Viktor Witkovsky (witkovsky@savba.sk) Ver.: 31-Jul-2014 18:27:32

This script reads in an image file and then attempts to find a green object in the image. It is designed to find one green ball and highlight that ball on the original image

If you have a set of N points on a cartesian plane, there will always exist an N-1th order polynomial of the form y = a_0 + a_1.x + a_2.x^2 + ... a_n-1.x^(n-1) which passes through all the points.

The Fibonacci numbers are an easily accessible area in number theory. As well, they appear in many places in mathematics and in nature , look here too . For those interested in reading more

Gaussian fit using the least-squared solution in presence of known covariance

Test the use of Forward-backward-like splitting for the resolution of a compressed sensing regularization.

How many of you have successfully solved a Rubik's Cube® before? How long did you take to solve a cube that your friend scrambled? I have been able to successfully solve a Rubik's Cube, but have

Copyright 2017 The MathWorks, Inc.

Copyright (c) 2008 Gabriel Peyre

Fit a polynomial curve to a set of data using polyfit. Use the polyfit function to find the coefficients of a polynomial that fits a set of data in a least-squares sense using the syntax

This script demonstrates testing a simple technical indicator strategy and backtesting to optimize its parameters

Model, configure, generate AUTOSAR compliant code and export xml files using Simulink® and Embedded Coder®. The Vehicle Speed and Odometer calculations example demonstrates this

Utility from File Exchange

Backward-compatible with Optimization Toolbox version 1.0

These prototype MATLAB functions create and plot graphs from images based on neighbor relationships between pixels. You must have MATLAB R2015b to use them.

Use array indexing to rasterize text into an existing image.

Create a chart using the bottom and left sides of the axes for the first plot and the top and right sides for the second plot.

How to create subplots in MATLAB®.

Create an animation of two growing lines. The animatedline function helps you to optimize line animations. It allows you to add new points to a line without redefining existing points.

How to create a 3D scatter plot in MATLAB®.

Based on "Finite Element Methods for flow problems" of Jean Donea and Antonio Huerta

This is a demonstration of using the topoplot_connect.m function. This function is only slightly modified from the original topoplot.m function which is part of EEGLAB. I have used EEGLAB

How to create wind flow visualization in MATLAB®.

This is an example showing standard markers available in MATLAB® plots.

The legappend function adds new entries to a legend. This is good for making PowerPoint slides, when you may want to start by plotting a few data sets, then add data to your plot one entry at a

How to create subplots with multiple plot types in MATLAB®.

How to create an inset plot within another plot in MATLAB®.

How to create a surface plot in MATLAB®.

How to create animations and animated GIFs in MATLAB®. In this example, we will animate the motion of a double-pendulum. We solve the ordinary differential equation using ode45.

This function creates a title centered at the top of a figure. This may be used to add a title to a figure with several subplots.

Implementation according to Fengler (2009) with example data taken from Appendix B.

This function plots formatted histograms. It's similar to hist, but with more options for FaceColor, BarWidth, LineStyle, FaceAlpha, etc.

Flow cytometry is a method for quantitating components or structural features of cells primarily by optical means. Although it makes measurements on one cell at a time, it can process

How to create a 2D scatter plot in MATLAB®.

How to create a histogram plot in MATLAB®.

Step through and execute this script cell-by-cell to verify a cell array implementation of the List Abstract Data Type (ADT).

Example 1: Bendat and piersol, Random data, 2010, page 99 Example 4.4

We illustrate how to find colorings of graphs and display the results.

We demonstrate how to split the vertex set of a graph into two parts using the split method. The goal is to separate the vertices of the graph into two natural clusters. The splitting is based on

This is a parameter sweep study of a 2nd order ODE system.

Only scalar variables need apply. Matrices and vectors would not be terribly difficult to implement, but I've not done so.

This demo illustrates how you would set up and solve an optimization problem (constrained non-linear minimization).

The function NUM2SIP converts a numeric scalar to a string containing the number value with a metric prefix, for example 1000 -> '1 k'. Optional arguments control the number of digits, select

The function NATSORT sorts a cell array of strings, taking into account any number values within the strings. This is known as a "natural order sort" or an "alphanumeric sort". Note that

This demo illustrates a simple approach to provide taxonomy annotation of BLAST hits. It requires the taxonomy information included in the files gi_taxid_prot.dmp and nodes.dmp, which

We demonstrate how to find a minimum dominating set in a graph. This requires Matlab's Optimization Toolbox. We illustrate this using Petersen's graph and a grid graph.

We specify a finite group by giving a list of its generators. The generators are a cell array of permutations of a common ground set.

This document demonstrates the usage of GENCODE, GENCODE_RVALUE and GENCODE_SUBSTRUCT to show and modify the contents of complicated MATLAB variables.

The errorshade function plots a shaded region to indicate gaussian uncertainty. This function works by generating an RGB image of a specified color, and setting transparency of the RGB

Solves a 2nd order wave equation: utt = uxx + uyy, with u = 0 on the boundaries. It uses a 2nd order central finite difference in time and a Chebyshev spectral method in space (using FFT). The code

Matgraph provides two functions for finding spanning trees:

We show that the the Ramsey number R(4) is greater than 17 by presenting a graph with 17 vertices that has clique and independence numbers equal to three. The Matgraph alpha and omega functions

The function WORDS2NUM converts a string (with a number given in English words) into a numeric value. Optional arguments control many string formatting and dialect options. The options are

The function SIP2NUM converts a string containing a number with a metric prefix into a numeric value, for example '1 k' -> 1000. The function is based on REGEXP, and can detect and convert

The nanimresize function resizes an image using the Image Processing toolbox function imresize, but first fills NaNs to prevent missing data along NaN boundaries.

Looking at Spring Damper System and comparing the results from the ODE45, ODE23, ODE15s solvers with the analytical solution.

The function NATSORTROWS sorts the rows of a cell array of strings, taking into account any number values within the strings. This is known as a "natural order sort" or an "alphanumeric sort".

Step through and execute this script cell-by-cell to verify the Singleton Desgin Pattern implementation in MATLAB.

Write a script that tests a function that you create. The example function computes the angles of a right triangle, and you create a script-based unit test to test the function.

The function NATSORTFILES sorts a cell array of filenames or filepaths, taking into account any number values within the strings. This is known as a "natural order sort" or an "alphanumeric

The following document was built from posts written for the blog "Loren on the Art of MATLAB". The ideas presented below in anonymous functions have been written as .m files so that they might

Write a unit test for a MATLAB® function, quadraticSolver.m.

This example shows how to generate code from packData and unpackData

QRcode_gen can generate QR-Codes based on the zxing libraries (http://github.com/zxing). For this purpose it will import all necessary jar files on the fly from a maven repository server

Compute normalized probability density function from characteristic function. Part of the CFH Toolbox.

We will now look at defining methods in the class definition file which are the operations that we can carry out with the class.

To monitor an object you first need to add an event to the class definition of the object, such as in this example. (see ev.m). Here we add an event called SavedData to this class which denotes

Compute spread option prices on the difference between to assets' price levels. Part of the CFH Toolbox.

Let's say that the sensor array data set was very large, taking up several GB. Althought you may modfiy it and you would never need to make a copy of it. In this case a handle class implementation

Pack and unpack data using the provided packData and unpackData functions

Returns the characteristic function evaluation of commonly encountered models in finance. Part of the CFH Toolbox.

Library of transforms (moment generating functions) of commonly ecountered jump distributions in finance. Part of the CFH Toolbox.

Jonas Almeida, April 2010

This is the most useful diagram for visualizing the contest. It shows the dramatic improvements that occur over time. Each passing entry is a dot, with its submission time on the x-axis and

This contribution presents a small tool to trace calls to methods and functions. There was no tracing tool for Matlab to find on the Internet and still isn't?

Compute call option prices from characteristic function. Part of the CFH Toolbox.

Matlab implementation of Flickr-compatible OAuth

Write a unit test for a couple of MATLAB® figure axes properties using fresh fixtures and file fixtures.

Compute bond prices for an AJD process. Part of the CFH Toolbox.

The function 'readImages' reads dicom image data from an image file or folder. Important attributes are stored in a convenient structure, which is used as the input for many other MATLAB

Simulation of acoustic beams from monoelement transducers is possible by using the objects, outside the NumSim simulation program. The visualization can be done using a GUI in Matlab or in

This is a Matlab GUI designed to view the points used in the kernels for interpolation purposes in the meshless formulation (resolution of boundary value problems).

David Young

Simple example which uses the features of resizable_figure and resizeable_layout. When the figure is resized, the edit control and the list control will expand to fill the available space.

This is a Matlab GUI designed to compute the acousto-electric conductivity modulation signal and Debye signals for a given electric geometry. Different parameters are included in this GUI

このチュートリアルでは、MATLABでアニメーションを作成する方法を学びます。 MATLABグラフのアニメーションを作成し、AVI形式のムービーやGIF形式のアニメーションを 作成します。

The following script is a tutorial on the methodology of what I call "Shape Prescriptive Modeling". Its a tool for modeling a function of a single variable

This script reverse-engineers charGUI and rebuilds it in a way that is both resizable and dockable. It does so using uipanel and positioning with normalized units.

HC_fcm:Horizontal Collaborative fcm by liyang @BNU Math 315 Email:farutoliyang@gmail.com 2009.09.25

This class provides a numeric editbox uicontrol.

Uses the "hgtable" functions to display a multi-column list

This is a simple example using the layout.GridBagLayout object to layout a simple figure with widgets. Resize layout is maintained automatically.

This function returns distances between mouse clicks on a map or cumulative distances along a path of mouse clicks on a map. Data points are entered by pressing a mouse button or any key on the

Find the maximum value of a single variable in a data set using mapreduce. It demonstrates the simplest use of mapreduce since there is only one key and minimal computation.

Use the readtable function to import mixed data from a text file into a table. Then, it shows how to modify and analyze the data in the table.

Visualize patterns in a large data set without having to load all of the observations into memory simultaneously. It demonstrates how to compute lower volume summaries of the data that are

Use mapreduce to carry out simple logistic regression using a single predictor. It demonstrates chaining multiple mapreduce calls to carry out an iterative algorithm. Since each

Compute the mean of a single variable in a data set using mapreduce. It demonstrates a simple use of mapreduce with one key, minimal computation, and an intermediate state (accumulating

Compute the mean by group in a data set using mapreduce. It demonstrates how to do computations on subgroups of data.

Extract a subset of a large data set.

Compute the mean and covariance for several variables in a large data set using mapreduce. It then uses the covariance to perform several follow-up calculations that do not require another

Compute summary statistics organized by group using mapreduce. It demonstrates the use of an anonymous function to pass an extra grouping parameter to a parameterized map function. This

Compute a tall skinny QR (TSQR) factorization using mapreduce. It demonstrates how to chain mapreduce calls to perform multiple iterations of factorizations, and uses the info argument of

Use high-level MATLAB® functions to import the sample CDF file, example.cdf. High-level functions provide a simpler interface to accessing CDF files.

Use ImageDatastore and mapreduce to find images with maximum hue, saturation and brightness values in an image collection.

Import worksheets in an Excel® file that contains only numeric data (no row or column headers, and no inner cells with text) into a structure array, using the importdata function.

Read numeric data and text headers from all worksheets in an Excel® file into a nested structure array, using the importadata function.

Use the findgroups and splitapply functions to calculate grouped statistics of a tall timetable containing power outage data. findgroups and splitapply enable you to break up tall

Create a datastore for key-value pair data in a MAT-file that is the output of mapreduce . Then, the example shows how to read all the data in the datastore and sort it. This example assumes that

Create text files, including combinations of numeric and character data and nonrectangular files, using the low-level fprintf function.

Use low-level functions to read data from a CDF file. The MATLAB® low-level CDF functions correspond to routines in the CDF C API library. To use the MATLAB CDF low-level functions

Create a datastore for a collection of images, read the image files, and find the images with the maximum average hue, saturation, and brightness (HSV). For a similar example on image

Import comma-separated numeric data from a text file, using the csvread function.

Create two different memory maps, and then read from each of the maps using the appropriate syntax. Then, it shows how to modify map properties and analyze your data.

Export a table in the workspace to a Microsoft® Excel® spreadsheet file, using the writetable function. You can export data from the workspace to any worksheet in the file, and to any location

Fit data with a linear model containing nonpolynomial terms.

Use tall arrays to work with big data in MATLAB®. You can use tall arrays to perform a variety of calculations on different types of data that does not fit in memory. These include basic

Read an arbitrary format text file with textscan . This function allows you to read the file one block at a time, and each block can have a different format.

MATLAB provides you with the tools to import spreadsheet data both interactively and programmatically. To interactively import spreadsheet data, see docid:import_export.br81u9o .

Use the datastore and mapreduce functions to process a large amount of file-based data. The MapReduce algorithm is a mainstay of many modern "big data" applications. This example operates

Stefan Güttel & Nick Hale, 13th December 2011

Nick Trefethen, October 2010

Tune the parameters and monitor the signals of an algorithm running on Tiva TM4C123G LaunchPad using Energia Toolchain.

Use Embedded Coder Support Package to run a Simulink® model on TIVA Tiva TM4C123G LaunchPad using Energia Toolchain.

Part1 - (Post) Data Visualization & feature extraction

Classify using supervised learning (FULL script)

Nick Trefethen, September 2010

This is short demo that loads and renders a 3D model of a human femur. It showcases some of MATLAB's advanced graphics features, including lighting and specular reflectance.

These function, mp3read and mp3write, aim to exactly duplicate the operation of wavread and wavwrite for accessing soundfiles, except the soundfiles are in Mpeg-Audio layer 3 (MP3)

Nick Trefethen, November 2010

Toby Driscoll, 20th December 2011

Nick Trefethen, 25th January 2012

Toby Driscoll and Nick Trefethen, October 2010

Cluster Analysis

F. Moisy, 19 nov 2008.

Nick Trefethen and Nick Hale, October 2010

Nick Trefethen, February 2011

Pedro Gonnet, September 2010

Nick Trefethen, 1st October 2011

Lloyd N. Trefethen, October 2009, revised February 2011

Lloyd N. Trefethen, November 2009, revised February 2011

Collect acceleration data from an Android device and use it to count the number of steps taken.

Collect position data from an Android device and display it on a map. Latitude and longitude coordinates are used to mark the device's route. Speed information is used to add color to the

Plot data from multiple sensors on an Android device together in one timeline. Measurements of angular velocity and orientation will be collected from the device and plotted over absolute

Collect position data from an Apple iOS device and display it on a map. Latitude and longitude coordinates are used to mark the device's route. Speed information is used to add color to the

Plot data from multiple sensors on an Apple iOS device together in one timeline. Measurements of angular velocity and orientation will be collected from the device and plotted over absolute

Collect acceleration data from an Apple iOS device and use it to count the number of steps taken.

Use the MATLAB® Support Package for Arduino® Hardware to use SPI interface to communicate with MCP42010 Digital Potentiometer.

Use the MATLAB® Support Package for Arduino® Hardware to control servo motors, DC motors and stepper motors using Adafruit motor shield v2.

Use MATLAB® Support Package for Arduino® Hardware to perform basic operations on the hardware such as turning an LED on and off, blinking LEDs and playing sound on a speaker.

Use the MATLAB® Support Package for Arduino® Hardware and the I2C interface to communicate with I2C devices.

Use the MATLAB® Support Package for Arduino® Hardware to control a hobby servo motor.

Use the MATLAB® Support Package for Arduino® Hardware to control a 1-Digit 7-Segment display with a 74HC595 8-bit serial-in-parallel-out shift register.

Use the MATLAB® Support Package for Arduino® Hardware to collect large number of push button states with a 74HC165 8-bit paralle-in-serial-out shift register. This example uses four push

Use the MATLAB® Support Package for Arduino® Hardware to control multiple LEDs with two 74HC595 8-bit serial-in-parallel-out shift registers.

Use the MATLAB® Support Package for Arduino® Hardware to steer a two-wheel Arduino-based robot with closed-loop control.

Use the MATLAB® Support Package for Arduino® Hardware to control a 12-step rotary encoder with a built-in push button.

Use the serial UART on BeagleBone Black hardware to control a 4-digit 7-segment display.

Use MATLAB to process images captured from a web camera on BeagleBone Black® board to track a green ball.

Use the SPI peripheral on BeagleBone Black® hardware to connect to an MCP3008 10-bit 8-channel ADC.

Use the I2C peripheral on BeagleBone Black® hardware to control a 4-digit 7-segment display.

You basics of working with BeagleBone Black® Hardware.

Use the MATLAB® Support Package for BeagleBone Black® Hardware to perform basic operations on the hardware such as executing shell commands, turning an on-board LED on or off and

Use the beaglebone function to create a connection to a BeagleBone Black hardware board and assign the connection to an object. You can use this object to interact with BeagleBone Black

Implement a closed-loop control algorithm to make a two-wheel LEGO® MINDSTORMS® EV3™ vehicle drive straighter.

Write a MATLAB script to implement a collision alarm with LEGO® MINDSTORMS® EV3™ hardware.

Interact with the EV3 brick peripherals, read a sensor value, and control a motor.

Set up communications with the EV3 brick.

Build a digital voltmeter using MATLAB® Support Package for Raspberry Pi® Hardware.

Build a motion sensor camera using MATLAB® Support Package for Raspberry Pi® Hardware.

Use MATLAB to process images captured from a Raspberry Pi Camera Board module to track a green ball.

Increase the number of digital I/O pins by connecting a MCP23017 I/O expander chip to the Raspberry Pi® hardware.

Capture and process images from Raspberry Pi® Camera Board module using the MATLAB® Support Package for Raspberry Pi Hardware.

Use the I2C peripheral on Raspberry Pi® hardware to control a 4-digit 7-segment display.

Use the MATLAB® Support Package for Raspberry Pi® Hardware to perform basic operations on the hardware such as executing shell commands, turning an on-board LED on or off and manipulating

Use the serial UART on Raspberry Pi hardware to control a 4-digit 7-segment display.

Use the SPI peripheral on Raspberry Pi® hardware to connect to an MCP3008 10-bit 8-channel ADC.

You basics of working with Raspberry Pi® Hardware.

Read the sensor values, read the position of joystick and control the LED Matrix on Raspberry Pi® Sense HAT using MATLAB® Support Package for Raspberry Pi Hardware.

Use MATLAB® to read the accelerometer on the Raspberry Pi Sense HAT and control the rotation of the image displayed on the LED matrix.

Use the snapshot function to acquire live images from USB Webcams.

Use the snapshot function to acquire live images and log the video to disk.

Copyright 2013 The MathWorks, Inc.Published with MATLAB® R2013a

Use the MATLAB® Support Package for Arduino® Hardware to control a HC-SR04 ultrasonic ranging module capable of measuring distances in the 2cm to 400cm range.

This function creates axes in tiled positions. It is similar to subplot, but uses the entire figure window with no space between subplots. The name smplot is used to invoke "Small Multiples"

This script shows how to connect to and execute query on a Mongo database from MATLAB. This script assumes it is connecting to a Mongo server version 3.0 This script works on MATLAB R2014b and

Use the MATLAB® Support Package for Arduino® Hardware to communicate with DS18B20 temperature sensor

This scripts demonstrates the capabilities of the heatmap visualization function.

I'm positive that some simple UML-diagrams could help us organizing our Matlab code. See UmlAsSketch by Martin Fowler.

Use the MATLAB® Support Package for Arduino® Hardware to control a three axis LSM303 accelerometer and magnetometer.

The eof function gives eigenmode maps of variability and corresponding principal component time series for spatiotemporal data analysis. It is designed specifically for 3D matricies of

The function COLORNAMES matches the input RGB values or color name strings to the closest colors from the selected palette. COLORNAMES returns the same outputs whether matching names or

Word error rate (WER) is a measure (metric) of the performance of an automatic speech recognition, machine translation etc.

Mark Text -> change Font -> change Background color

Use the MATLAB® Support Package for Arduino® Hardware to control a three-axis L3G gyroscope that measures the angular rates of rotation about the roll(X), pitch(Y) and yaw(Z) axes.

Use the MATLAB® Support Package for Arduino® Hardware to control a capacitive sensor built with foil connected between two digital pins on Arduino.

Collect and then display latitude and longitude data on a satellite map image.

You can create a PDF or HTML version of this MATLAB file by choosing opening it in the MATLAB Editor and choosing "File > Publish ..."

This tutorial demonstrates the use of the Optical Fibre Toolbox for calculation of the three-layer (core-cladding-surrounding) fibres. First, the specification of such structures is

Capture the orientation of the mobile device. We define the orientation as a combination of three angular quantities: Azimuth, pitch, and roll. The three quantities are defined based on the

Abaqus2Matlab is a Matlab toolbox which is used to retrieve the results of an Abaqus analysis in an easy to handle form. It is developed by George Papazafeiropoulos

Choose your country to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a location from the following list:

See all countries