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.

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 :

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

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

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

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

Flip multiple matrices along specified dimensions.

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

This function clears all empty variables from the current workspace.

Test to have one double

Add the cell of names to a string

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.

Fill in gaps in timetable variables, using different methods for different variables. You can specify whether each timetable variable contains continuous or discrete data using the

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

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

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.

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

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

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

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

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

Copyright (c) 2008 Gabriel Peyre

Utility from File Exchange

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.

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

This demo file teaches about the aliquot parts of a number, and how to use the functions I've provided.

Spl returns sound pressure level in decibels for an input signal p_Pa in pascals. A reference pressure ref must be declared in units of pascals or specified as 'air' or 'water' to use standard

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

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

Backward-compatible with Optimization Toolbox version 1.0

Copyright 2017 The MathWorks, Inc.

How to create subplots in MATLAB®.

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

How to create wind flow visualization in MATLAB®.

Use array indexing to rasterize text into an existing image.

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

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

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

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

In this example, a 2-dimensional random point set is given, which has an internal cavity. The idea for the concave hull creation is to create the convex hull of the given point set (point set 1)

Animates the vibration of a membrane, captures a series of screen shots, and saves the animation as a GIF image file.

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.

Set the random number generator.

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

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.

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

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

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.

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

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.

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

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.

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

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.

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.

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

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

Matgraph provides two functions for finding spanning trees:

The function ROUND60063 rounds the input numeric values to values from the IEC 60063 "Preferred Numbers" series. Most importantly ROUND60063 simulates the tolerance range of electronic

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 WORDS2NUM converts a string (with a number given in English words) into a numeric value, e.g. 'one thousand and twenty-four' -> 1024. Optional arguments control many string

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

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

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

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

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

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

This example shows how to generate code from packData and unpackData

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

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

Pack and unpack data using the provided packData and unpackData functions

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

Jonas Almeida, April 2010

Matlab implementation of Flickr-compatible OAuth

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

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 spread option prices on the difference between to assets' price levels. Part of the CFH Toolbox.

Library of transforms (moment generating functions) of commonly ecountered jump distributions in finance. 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

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

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

This script uses the class definition TestClass to create instances of TestClass and to clone its instances.

This presentation proceeds in stages, each version an extension of its predecessor (bootstrapping). The development stops well short of an industrial compiler but that is not because of

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

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

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

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

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

David Young

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形式のアニメーションを 作成します。

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 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 class provides a numeric editbox uicontrol.

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

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.

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

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

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.

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.

Import mixed numeric and text data into separate arrays in MATLAB®, using the xlsread function.

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

Several different ways you can visualize tall arrays.

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

This Live Script file will be presented to your end user in the Live Editor just as you see it here. You can take advantage of all of the features of Live Script to present information and

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)

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)

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.

F. Moisy, 19 nov 2008.

Cluster Analysis

Youtube released an updated version of their Youtube Data API:

Illustrates the use of BEADS to estimate and remove the baseline of chromatogram series.

This is a simple example of using regularizeNd.

This script file is designed to be used in cell mode from the matlab editor, or best of all, use the publish to HTML feature from the matlab editor. Older versions of matlab can copy and paste

RegularizeNd Fits a nD lookup table with smoothness to scattered data.

How we can use the JSON parser to take data directly from Trendy (such as this trend for Cody problem count) and bring them into MATLAB.

By Kotya Karapetyan, kotya.karapetyan@gmail.com, 2011--2012.

UML Sequence Diagrams are a good way to express flow control in a program, or show the lifetime of objects in an OO system.

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 the MATLAB® Support Package for Arduino® Hardware and the I2C interface to communicate with I2C devices.

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

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 scripts demonstrates the capabilities of the heatmap visualization function.

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

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"

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

Mark Text -> change Font -> change Background color

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

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

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.

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

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

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

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.

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

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

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