MATLAB Examples

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

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.

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

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

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.

Access and modify table properties for variable units, descriptions and names. You also can edit these property values using the Variables Editor.

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

Add and subtract date and time values to calculate future and past dates and elapsed durations in exact units or calendar units. You can add, subtract, multiply, and divide date and time

Add and delete column-oriented variables in a table. You also can edit tables using the Variables Editor.

Plot data from a categorical array.

Create a table from a subset of a larger table.

Two ways to extract date and time components from existing datetime arrays: accessing the array properties or calling a function. Then, the example shows how to modify the date and time

Compare datetime and duration arrays. You can perform an element-by-element comparison of values in two datetime arrays or two duration arrays using relational operators, such as > and <.

Extract the contents of a table using curly braces or dot indexing.

Use the linspace function to create equally spaced datetime or duration values between two specified endpoints.

Use relational operations with a categorical array.

Compare the memory required to store data as a cell array of character vectors versus a categorical array. Categorical arrays have categories that are defined as character vectors, which

Index and search using categorical arrays. You can access data using categorical arrays stored within a table in a similar manner.

Convert a variable in a table from a cell array of character vectors to a categorical array.

Use the colon (:) operator to generate sequences of datetime or duration values in the same way that you create regularly spaced numeric vectors.

Add a duration or calendar duration to a datetime to create a sequence of datetime values.

Use the dateshift function to generate sequences of dates and time where each instance obeys a rule relating to a calendar unit or a unit of time. For instance, each datetime must occur at the

Create a categorical array. categorical is a data type for storing data with values from a finite set of discrete categories. These categories can have a natural order, but it is not required.

Combine two categorical arrays.

Request specific outputs from a function.

Create an ordinal categorical array using the categorical function with the 'Ordinal',true name-value pair argument.

Use uniquetol to find the average z-coordinate of 3-D points that have similar (within tolerance) x and y coordinates.

Group scattered data points based on their proximity to points of interest.

The alpha shape of a set of points is a generalization of the convex hull and a subgraph of the Delaunay triangulation. That is, the convex hull is just one type of alpha shape, and the full family

The convex hull of a set of points in N-D space is the smallest convex region enclosing all points in the set. If you think of a 2-D set of points as pegs in a peg board, the convex hull of that set

Use scatteredInterpolant to interpolate a scattered sampling of the peaks function.

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

The Voronoi diagram and the Delaunay triangulation on the same 2-D plot.

Create and plot a 2-D interpolant using griddedInterpolant.

Smooth traffic flow data using a moving-average filter with a 4-hour sliding window. The following difference equation describes a filter that averages the current hour and the three

Analyzes the frequency spectrum of audio data.

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

Extrapolate a well sampled 3-D gridded dataset using scatteredInterpolant. The query points lie on a planar grid that is completely outside domain.

Integrate a set of discrete velocity data numerically using trapz to approximate the total distance traveled. The integral family only accepts function handles as inputs, so those

Use convolution to smooth 2-D data that contains high-frequency components.

It is often useful to use a graphical format to view the distribution of the nonzero elements within a sparse matrix. The MATLAB spy function produces a template view of the sparsity

Create and plot a 1-D interpolant using griddedInterpolant with a cubic interpolation method.

Plot the imaginary part versus the real part of a complex vector, z. With complex inputs, plot(z) is equivalent to plot(real(z),imag(z)), where real(z) is the real part of z and imag(z) is the

The Delaunay triangulation is well suited to scattered data interpolation problems because it has favorable geometric properties that produce good results. These properties are:

Modify the amplitude of a vector of data by applying a transfer function.

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

Reduce the dimensionality of the grid plane arrays in 3-D to solve a 2-D interpolation problem.

Create a 3-D interpolant and evaluate over a slice plane so you can plot the values on that plane.

Interpolate scattered data when the value at each sample location is complex.

The relationship between a Delaunay triangulation of a set of points in 2-D and the convex hull of that set of points.

Interpolate two different samplings of the same parabolic function. It also shows that a better distribution of sample points produces better extrapolation results.

Plot more than one line by passing multiple x,y pairs to the plot function.

Determine the minimum and maximum data points on a graph and add text descriptions next to these values.

Create a graph in a new figure window, instead of plotting into the current figure.

Change the grid line style using the GridLineStyle and MinorGridLineStyle axes properties. Line style options are a solid line, '-', a dotted line, ':', a dashed line, '--', and a

Plot only the data points by omitting the line style option from the line specification.

Use a loop to create a figure containing four subplots. In each subplot, plot a sine wave with different frequencies based on the loop variable k. Add a title to each subplot that includes the

Display major and minor grid lines on a graph. Major grid lines align with the tick mark locations. Minor grid lines appear between the tick marks.

Create a figure containing multiple axes using the subplot function. The syntax, subplot(m,n,p), divides the figure into an m-by-n grid with an axes in the pth grid location. The grids are

Create a line plot and add a title and axis labels to the graph. Display a superscript in the title using the ^ character. The ^ character modifies the character immediately following it.

The hist function accepts bin centers, whereas the histogram function accepts bin edges. To update code to use histogram, you might need to convert bin centers to bin edges to reproduce

Plot the sine function and plot two polynomials.

Include a variable value in the x-axis label. Use the num2str function to convert the number to text.

Rotate a surface about the y-axis.

Use array indexing to rasterize text into an existing image.

Add a title, axis labels and a legend to a graph using the title, xlabel, ylabel and legend functions. By default, these functions add the text to the current axes. The current axes is typically

Modify a 3-D bar plot by coloring each bar according to its height.

Specify the line style, color, and markers for two sine waves. If you specify a marker type, then plot adds a marker to each data point.

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

Change the width of the colorbar by setting its Position property. The Position property sets the location and size of the colorbar. Specify the Position property value as a four-element

Plot . Draw a vertical line at from the x-axis to the plotted line.

Add a legend to a pie chart that displays a description for each slice.

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.

Plot two sine waves with different line styles by adding a line specification to each x,y pair.

Anonymous functions require that you explicitly specify the input arguments as you would for a standard function, separating multiple inputs with commas. For example, this function

Anonymous functions allow you to define a function without creating a program file, as long as the function consists of a single statement. A common application of anonymous functions is to

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.

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

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

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

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

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

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 nanimresize function resizes an image using the Image Processing toolbox function imresize, but first fills NaNs to prevent missing data along NaN boundaries.

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

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

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

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

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

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

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.

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.

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

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

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

This example shows how to generate code from packData and unpackData

Pass a multilevel pointer to a C function.

This example was authored by the MathWorks community.

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

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

Pass a MATLAB character array str to a C function, stringToUpper.

Pass data stored columnwise in a MATLAB array to a C function that assumes a row-by-column format.

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

Ïnteger weights of items

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

Create a MATLAB® cell array of character vectors, mlStringArray, from the output of the getListOfStrings function.

Preconvert structure sm to c_struct before calling addStructFields. If you repeatedly pass sm to functions, preconverting eliminates the processing time required by MATLAB to

Pass enumeration values to the readEnum function in the shrlibsample library. Load the library.

Pass a MATLAB structure to the function, addStructFields.

How calling the addStructByRef function with a pointer modifies the fields in the input argument.

Use pointer arithmetic to access elements of a structure. The example creates a MATLAB structure, based on the c_struct definition in the shrlibsample.h header file.

Returns the characteristic function evaluation of commonly encountered models in finance. 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

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.

David Young

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

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

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

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

Export a cell array to a text file, using the fprintf function.

Export a table to a text file, using the writetable function.

Remove a linear trend from daily closing stock prices to emphasize the price fluctuations about the overall increase. If the data does have a trend, detrending it forces its mean to zero and

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 MATLAB® HDF5 low-level functions to write a data set to an HDF5 file and then read the data set from the file.

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

Import numeric data delimited by any single character using the dlmread function.

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.

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

Create a datastore for a large text file containing tabular data, and then read and process the data one chunk at a time or one file at a time.

Use multiple regression to model data that is a function of more than one predictior variable.

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

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

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

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.

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

Append values to an existing text file, rewrite the entire file, and overwrite only a portion of the file.

Fit data with a linear model containing nonpolynomial terms.

Get information about the dimensions, variables, and attributes in a NetCDF file using MATLAB low-level functions in the netcdf package. To use these functions effectively, you should be

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

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

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.

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

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

Nick Trefethen, 25th January 2012

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

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

F. Moisy, 19 nov 2008.

Toby Driscoll, 20th December 2011

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, October 2009, revised February 2011

Nick Trefethen, November 2010

Cluster Analysis

Alex Townsend, 6th May 2011

Lloyd N. Trefethen, November 2009, revised February 2011

Youtube released an updated version of their Youtube Data API:

Nick Trefethen and Nick Hale, October 2010

Nick Trefethen, October 2010

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.

Stefan Güttel & Nick Hale, 13th December 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 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.

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® SenseHAT using MATLAB® Support Package for Raspberry Pi Hardware.

Use MATLAB® to read the accelerometer on 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

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 control a HC-SR04 ultrasonic ranging module capable of measuring distances in the 2cm to 400cm range.

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

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 communicate with DS18B20 temperature sensor

Copyright (c) 2008 Gabriel Peyre

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

This scripts demonstrates the capabilities of the heatmap visualization function.

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

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

M2uml 1.1 includes new feaures

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

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

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

The circleps function plots circles of given radii on an Antarctic polar stereographic projection map. Latitude of true scale is 71S.

Get new value of sigma^(-2)

This document will help you get set up and running with the roatmanTrader functionality for connecting to Rotman Interactive Trader.

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

Authors: Caterina Samela (caterina.samela@unibas.it); Salvatore Manfreda

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