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.

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.

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

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

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

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

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

Use relational operations with a categorical array.

You can search for text in character arrays and string arrays, and replace substrings with new text. String arrays, and new functions to search for and replace text, were introduced in

Create a scatter plot with datetime or duration inputs using the scatter or scatter3 functions. For example, create a scatter plot with dates along the x -axis.

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

Create a table from workspace variables, work with table data, and write tables to files for later use. table is a data type for collecting heterogeneous data and metadata properties such as

Add, delete, and rearrange column-oriented variables in a table. You can add, move, and delete table variables using the addvars , movevars , and removevars functions. As alternatives, you

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

You can combine timetables and synchronize their data in a variety of ways. You can concatenate timetables vertically or horizontally, but only when they contain the same row times or

Use the times function to combine categorical arrays, including ordinal categorical arrays and arrays with undefined elements. When you call times on two categorical arrays, the output is

Store text from a file as a string array, sort the words by their frequency, plot the result, and collect basic statistics for the words found in the file.

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

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

Split power outage data from a table into groups by region and cause of the power outages. Then it shows how to apply functions to calculate statistics for each group and collect the results in a

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

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

String arrays were introduced in R2016b. String arrays store pieces of text and provide a set of functions for working with text as data. You can index into, reshape, and concatenate strings

Resample and aggregate data in a timetable. A timetable is a type of table that associates a time with each row. A timetable can store column-oriented data variables that have different data

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

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

Define a function that visualizes the results of bfsearch and dfsearch by highlighting the nodes and edges of a graph.

Customize the GraphPlot data cursor to display extra node properties of a graph.

This page contains two examples of solving nonstiff ordinary differential equations using ode45. MATLAB® has three solvers for nonstiff ODEs.

Construct and analyze a Watts-Strogatz small-world graph. The Watts-Strogatz model is a random graph that has small-world network properties, such as clustering and short average path

Write a simple event function for use with an ODE solver. The example file ballode models the motion of a bouncing ball. The events function halts the integration each time the ball bounces,

Use the directional components of an event function. The example file orbitode simulates a restricted three body problem where one body is orbiting two much larger bodies. The events

This page contains two examples of solving stiff ordinary differential equations using ode15s. MATLAB® has four solvers designed for stiff ODEs.

Fit a nonlinear function to data. For this example, the nonlinear function is the standard exponential decay curve

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

Split the integration domain to place a singularity on the boundary.

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

You can use convolution to smooth 2-D data that contains high-frequency components.

The filter function is one way to implement a moving-average filter, which is a common data smoothing technique.

Integrate a set of discrete velocity data numerically to approximate the distance traveled. The integral family only accepts function handles as inputs, so those functions cannot be used

Use the Laplacian matrix of a graph to compute the Fiedler vector. The Fiedler vector can be used to partition the graph into two subgraphs.

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

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

Perform nearest-neighbor interpolation on a scattered set of points using a specific Delaunay triangulation.

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

Calculate complex line integrals using the 'Waypoints' option of the integral function. In MATLAB®, you use the 'Waypoints' option to define a sequence of straight line paths from the first

Use the polyint function to integrate polynomial expressions analytically. Use this function to evaluate indefinite integral expressions of polynomials.

Add attributes to the nodes and edges in graphs created using graph and digraph . You can specify node names or edge weights when you originally call graph or digraph to create a graph. However,

Use array indexing to rasterize text into an existing image.

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.

Create a line plot with markers. Customize the markers by setting these properties using name-value pair arguments with the plot function:

Modify the marker locations, then revert back to the default locations.

Create a line plot with 1,000 data points, add asterisks markers, and control the marker positions using the MarkerIndices property. Set the property to the indices of the data points where

Create a line plot. Display a marker at each data point by including the line-specification input argument when calling the plot function. For example, use '-o' for a solid line with circle

Move a group of objects together along a line using transforms.

Create a scatter plot using blue, semitransparent markers. Then, add a second scatter plot using red, semitransparent markers. Specify the marker color by setting the MarkerFaceColor and

Plot y = x^2\sin(x) . Draw a vertical line at x = 2 from the x -axis to the plotted line.

Plot the sine function and plot two polynomials.

Change the colors used in a filled contour plot.

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.

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

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

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

Label each contour line with its associated value.

Animate a triangle looping around the inside of a circle by updating the data properties of the triangle.

Create a plot using a dashed line. Add the optional line specification, '--' , to the x,y pair.

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

Highlight contours at particular levels.

Create a vector of random data and find the index of the minimum and maximum values. Then, create a line plot of the data. Display red markers at the minimum and maximum data values by setting the

Rotate a surface about the y -axis.

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

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 script-based test that uses local functions as helper functions. The example function approximates the sine and cosine of an angle. The script-based test checks the approximation

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

Request specific outputs from a 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

Use nested functions to easily share data, as well as for creating customized functions.

Is an introduction to the Live Editor. In the Live Editor, you can create live scripts that show output together with the code that produced it. Add formatted text, equations, images, and

Test a function that you create by writing a live script, 'TestRightTriLiveScriptExample.mlx' . The example function computes the angles of a right triangle, and you create a

Define functions at the command line with anonymous functions.

Add interactive controls to a live script. Adding interactive controls to a live script is useful when you want to share the live script with others. Use interactive controls to set and change

Use the output of one MATLAB® function as an input to another. This ability to specify a function's output as an input of another function serves a wide variety of purposes. Here we illustrate

The following is an example of how to use the Live Editor to create an interactive narrative. Create an interactive narrative to tell a story with computations that you have used to solve a

The following is an example of how to use the Live Editor to accelerate exploratory programming. This example demonstrates how you can use the Live Editor to:

MATLAB ® scripts, including live scripts, can contain code to define functions. These functions are called local functions.

The following is an example of how to use live scripts in the classroom. This example shows how to:

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.

Use Python® language functions and modules within MATLAB®. The example calls a text-formatting module from the Python standard library.

Pass a MATLAB structure to the function, addStructFields .

Create a pointer to a subset of a MATLAB vector X . The new pointer is valid only as long as the original pointer exists.

Construct and pass a pointer to C function multDoubleRef .

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.

How a C function changes the dimensions of a MATLAB array, and how to restore its shape.

Pass a MATLAB structure to a C library function, addStructByRef . When you pass the structure, MATLAB automatically converts the field types, but MATLAB also makes a copy of the fields.

Pass a multilevel pointer to a C function.

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

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

Display information about and modify a libstruct object, c_struct .

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.

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.

Add a plugin to the test runner. The matlab.unittest.plugins.TestRunProgressPlugin displays progress messages about a test case. This plugin is part of the matlab.unittest package.

Use a System.String object in a MATLAB® function.

Update a Python® list of folder names using the append method.

Use the whiteboard System object. Each time you run the object, it draws a line on a whiteboard.

Analyze the information returned by a test runner created from the SolverTest test case.

Display elements in a tuple.

To open the example in GUIDE, click the button on this page. To run the app, click the green Run Figure button at the top of the GUIDE window.

To open the example in GUIDE, click the button on this page. To run the app and allow it to show the contents of the current folder, click the Run Figure (green play button) at the top of the GUIDE

This app shows how to define two tabs to list and plot data. One tab contains a chart and a few user interface components for adjusting the chart. The other tab displays a table that lists the data

This app consists of a main plotting app that has a button for selecting options in a dialog box. The Plot Options button calls the dialog box app with input arguments. The CloseRequestFcn

This app shows how to use numeric edit fields to create a simple mortgage amortization calculator. It includes the following components to collect user input, calculate monthly payments,

This app shows how to display a Table UI component in an app that uses table array data. The table array contains numeric, logical, catgeorical, and multicolumn variables.

This app contains a gauge that tracks the value of a slider as the user moves the thumb. The ValueChangingFcn callback for the slider gets the current value of the slider from the event

This app shows how to add a tree to an App Designer app. The app selects data from patients.xls and displays it in a hierarchy using a tree. The tree contains three nodes that display hospital

Create a user interface with tab panels in MATLAB®.

This app shows how to dynamically add tree nodes at run time. The three hospital nodes exist in the tree before the app runs. However at run time, the app adds several child nodes under each

Here is a prebuilt GUIDE app that uses application data and the guidata function to share data between two dialog boxes. When you enter text in the second dialog box and click OK, the button

Create a graphical table in a user interface using uitable. It also shows how to modify the appearance of the table and how to restrict the changes users can make to the data in the table.

Here is a prebuilt GUIDE app that uses guidata and UserData to share data among three app windows. The large window is an icon editor that accepts information from the tool palette and color

This app shows how to share data in a private property and a drop-down list. It has a private property called Z that stores plot data. The callback function for the edit field updates Z when the

This app shows how to create a helper function that initializes two plots and updates them in a component callback. The app calls the updateplot function at the end of the StartupFcn callback

Here is a prebuilt GUIDE app that uses the guidata function to share data between a slider and a text field. When you move the slider, the number displayed in the text field changes to show the new

This app shows how to generate a pulse from instrumentation controls. It uses the following components to gather user input and plot the resulting wave form:

To run the tutorial in App Designer, click the Open Example button on this page. Alternatively, you can run the tutorial by selecting Open > Interactive Tutorial on the Designer tab in the App

This app shows how to display a confirmation dialog box that executes a callback when the dialog box closes.

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.

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

Fit data with a linear model containing nonpolynomial terms.

Use low-level functions to write data to a NetCDF file. The MATLAB® low-level functions provide access to the routines in the NetCDF C library. MATLAB groups the functions into a package,

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

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

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.

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

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

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

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 steer a two-wheel Arduino-based robot with closed-loop control.

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 control a hobby servo motor.

Use the MATLAB® Support Package for Arduino® Hardware to control servo motors, DC motors, and stepper motors using the Adafruit Motor Shield V2.

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

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

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

Choose a web site 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 web site from the following list:

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Contact your local office