MATLAB Examples

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

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.

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:

Place the UserDefinedConstants directory on your MATLAB search path

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 function clears all empty variables from the current workspace.

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,

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

Add the cell of names to a string

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

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

This example was authored by the MathWorks community.

Test to have one integer

Flip multiple matrices along specified dimensions.

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.

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.

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

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

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

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

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

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

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

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

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

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

Copyright (c) 2008 Gabriel Peyre

Utility from File Exchange

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.

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 subplots in MATLAB®.

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

How to create a surface plot in MATLAB®.

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 a 3D scatter plot in MATLAB®.

How to create wind flow visualization in MATLAB®.

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

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

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

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

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

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.

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

The function NUM2WORDS converts a numeric scalar into a string with the number value given in English words. Optional arguments control both the handling of the numeric input, as well as many

The function NUM2SIP converts a numeric scalar to a string containing the number value with a metric prefix, for example 1000 -> '1 k'. The coefficient of the returned string value is between 1

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

Matgraph provides two functions for finding spanning trees:

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.

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

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.

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

This example shows how to generate code from packData and unpackData

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 couple of MATLAB® figure axes properties using fresh fixtures and file fixtures.

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

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

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

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

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

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

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.

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

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

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

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

Matlab implementation of Flickr-compatible OAuth

Jonas Almeida, April 2010

We are going to create a class to describe the sensor array data set. First we will look at specifying the properties. You define a class in MATLAB with a class definition file.

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?

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

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.

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

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

このチュートリアルでは、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

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

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

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

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

This class provides a numeric editbox uicontrol.

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

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.

Nick Trefethen, October 2010

Nick Trefethen, 25th January 2012

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.

Classify using supervised learning (FULL script)

Part1 - (Post) Data Visualization & feature extraction

Nick Trefethen, November 2010

F. Moisy, 19 nov 2008.

Toby Driscoll, 20th December 2011

Nick Trefethen and Nick Hale, October 2010

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)

Lloyd N. Trefethen, November 2009, revised February 2011

Cluster Analysis

Alex Townsend, 6th May 2011

Toby Driscoll and Nick Trefethen, October 2010

Lloyd N. Trefethen, October 2009, revised February 2011

Nick Trefethen, September 2010

Youtube released an updated version of their Youtube Data API:

Pedro Gonnet, September 2010

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.

You basics of working with Raspberry Pi® Hardware.

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

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"

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

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

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

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

This scripts demonstrates the capabilities of the heatmap visualization function.

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

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

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

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

Computes a highest density contour for a given exceedance probability. Currently works for probability density functions with up to 4 dimensions.

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.

Get new value of sigma^(-2)

M2uml 1.1 includes new feaures

This highest density contour (HDC) implementation works up to 4 dimensions.

The measures_displacement function predicts the horizontal location of a parcel of ice after a specified amount of time, based on InSAR surface velocities. This function does not account

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

There are an awful lot of polar datasets out there, and each one seems to be packaged in a different format. Antarctic Mapping Tools is a collection of functions intended to streamline the

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