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 :

Example 1: addcd, show, reset

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?

This example was authored by the MathWorks community.

This file demonstrates how to use the Par class object to time the execution time of each PARFOR loop. Here are the steps.

Open the current working directory

Open a MATLAB file

Go up one level

Open the folder containing the current file

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

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 R2016b

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

And Generate Code to Run Algorithms on Raspberry Pi

Utility from File Exchange

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

Demonstrates building and validating a short term electricity load forecasting model with MATLAB. The models take into account multiple sources of information including temperatures

Fit a polynomial curve to a set of data points using the polyfit function. You can use polyfit to find the coefficients of a polynomial that fits a set of data in a least-squares sense using the

本プログラムでは、MATLAB上でSegNetを構築・学習し、 学習済みネットワークを評価するところまでのワークフローを試行します。 画像データは血液塗抹標本画像を利用し、写っている寄生虫の部分、赤血球の部分と それ以外の領域の3クラスに分類することを目的とします。 画像データは米国CDC DPDx Parasite Image

本プログラムでは、MATLAB上でFCN-AlexNetを構築・学習し、 学習済みネットワークを評価するところまでのワークフローを試行します。 画像データはCamVidデータセットを利用します。詳細についてはReference[1]をご覧ください。

Number of rows in healthy file must be the same as the number of rows in disease file. This reflects the fact that both must have measured the same number of quantities (genes, compounds, bugs,

Demonstrates building and validating a short term electricity price forecasting model with MATLAB using Neural Networks. The models take into account multiple sources of information

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

This examples illustrates how to perform a FORM analysis on a discrete (0 or 1) failure response. In the example we'll compare a traditional Monte Carlo method with FORM. This example is was

This is the third script of 4 in the Natural Gas Storage Valuation case study. In this script, we calibrate a forward curve model to historical and options-derived forward curve data. The

Demonstrates computing Value-at-Risk and Conditional Value-at-Risk (expected shortfall) for a portfolio using multivariate copula simulation with fat-tailed marginal

Coorous Mohtadi, MathWorks, 2012

Copyright 2017 The MathWorks, Inc.

This document explains how to use the state space MPC function which using input increment.

Simulates the movements of a swarm to minimize the objective function

This script aims at demonstrating the capabilities and the syntax of simpletracker.m, a MATLAB function dedicated to tracking.

In this demo, we use optimization to find optimal bang-coast-bang acceleration basis functions. Acceleration function is calculated to minimize swing of payload. Dynamic equations used

Use array indexing to rasterize text into an existing image.

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

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.

The c130 function draws a simple 3D airplane modelled after the Lockheed C-130.

By Jarek Tuszynski (jaroslaw.w.tuszynski@leidos.com)

Copyright (c) 2008 Gabriel Peyre

Set the random number generator.

From http://code.google.com/creative/radiohead/:

A convex polytope P can be specified in two ways:

PINPOLYHEDRON: This function is an implementation of a novel algorithm. It tests whether points are inside/outside/on a polyhedron defined by triangular faces and vertices. It can be used

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)

The function NUM2WORDS converts a numeric scalar into a string with the number value given in English words, e.g. 1024 -> 'one thousand and twenty-four'. Optional arguments control the

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

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

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

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

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

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

Fit an equation to data which has a sudden discontinuity using the Curve Fitting Toolbox.

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

We show how to determine if two graphs are isomorphic and, if so, how to find the permutation that transforms one into the other.

We illustrate the use of bipmatch to find maximum matchings in bipartite graphs.

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

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.

The imagescn behaves just like imagesc, but makes NaNs transparent, sets axis to xy if xdata and ydata are included, and has more error checking than imagesc.

We illustrate how to find a Hamiltonian cycle in a graph, convert that cycle into a subgraph, and then display the results.

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

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.

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

Compiled by Jason Nicholson, Edited by Richard Johnson, Version 1.5, 2018-January-29

The euler_trail function finds Eulerian trails and tours in graphs.

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.

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

Copyright 2012-2018 The MathWorks, Inc.Published with MATLAB® R2017a

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

Copyright 2015-2018 The MathWorks, Inc.Published with MATLAB® R2017a

Copyright 2017-2018 The MathWorks, Inc.Published with MATLAB® R2017a

Velocimetry (PIV) to determine the trajectory of particles accelerated inside an acoustophoretic device as result of an ultrasonic standing wave field.

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 simple example using the layout.GridBagLayout object to layout a simple figure with widgets. Resize layout is maintained automatically.

The aim of this analysis is to characterize the dose response behavior of 4 different drug candidates in a population. The objective of this analysis is investigate the how the treatments

This file contains an explanation of the difference between implicit and explicit time integration schemes. The content is intended for those who want to learn a bit more than what the

This Matlab tutorial demonstrates step by step the Singular Spectrum Analysis (SSA).

Author: SHUJAAT KHAN -- shujaat123@gmail.com Cite: Khan, S., Naseem, I., Togneri, R. et al. Circuits Syst Signal Process (2017) 36: 1639. doi:10.1007/s00034-016-0375-7

This simulation code is based on "Jordan Street's" OFDM simulation presentation 'https://www.youtube.com/watch?v=SyKJrrNhPO8'. We just implemented this tutorial. We don't claim any

Khan, S., Naseem, I., Togneri, R. et al. Circuits Syst Signal Process (2017) 36: 1639. doi:10.1007/s00034-016-0375-7 https://link.springer.com/article/10.1007/s00034-016-0375-7

This Matlab tutorial demonstrates step by step the multivariate singular spectrum analysis. The steps are almost similar to those of a singular spectrum analysis.

When you are loading large files for lookup table data from a mat file, the loading of the file is a major cost of time when running the Simulink model. The time cost can be reduced by keeping the

必要なToolbox:

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

Author: Shujaat Khan, shujaat123@gmail.com

Toby Driscoll, November 10, 2010

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

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

The behavior of regularizeNd in 1D.

Author: Shujaat Khan, shujaat123@gmail.com Please Cite: Khan, S., Naseem, I., Togneri, R. et al. Circuits Syst Signal Process (2017) 36: 1639. doi:10.1007/s00034-016-0375-7

Demonstrates the use of regularizeNd with a 4D input and 1D output dataset. Note, that selecting the smoothness isn't always obvious until you have gained experience using regularizeNd.

This is a 5d example. The number of points in the grid is 117,600. This means that the rank of the linear system equations solved is 117,600. I would classify this as a medium size problem. In my

Plant identification simulation Author: SHUJAAT KHAN (shujaat123@gmail.com) Please cite: @article{Khan2017FLMFFL, title={FLMF: Fractional least mean fourth algorithm for channel

This Matlab tutorial demonstrates the application of a modified varimax algorithm in varimax.m to the eigenvectors of a multichannel singular spectrum analysis (M-SSA).

Easy to build pendulum lab to acquire data from an Arduino®, analyze the data to find the period of the pendulum, and connect theory with the experiment using symbolic calculations.

The difference between the '\' and the 'normal' solver. The gist is use the '\' for accuracy or ill conditioned problems otherwise use 'normal' for speed. 'normal' is 2-3 times faster than '\'

By Jarek Tuszynski

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

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

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

Example spreadsheet from a brain imaging study

This paper discusses several approaches for calling shared libraries from Simulink models.

If hot=true, the database structure is modified as needed. e.g, when you get a table with d.table('tablex'), tablex is automatically created. Similarly, when you insert entries into

Popen() -- for "pipe open" -- is a very useful system call provided in many flavors of Unix. It runs a command passed in as a string then returns a file handle so that the parent process can read or

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

Pack and unpack data using the provided packData and unpackData functions

This example shows how to generate code from packData and unpackData

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

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.

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

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. Create a sample file, read all the data in the file, and then read only a subset starting from a specified location.

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

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.

Access parts of variables from a MAT-file dynamically. This is useful when working with MAT-files whose variables names are not always known.

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 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 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 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 and the I2C interface to communicate with I2C devices.

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 SPI peripheral on BeagleBone Black® hardware to connect to an MCP3008 10-bit 8-channel ADC.

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

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

You basics of working with BeagleBone Black® Hardware.

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

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

Set up communications with the EV3 brick.

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

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

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

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

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

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

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

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

You basics of working with Raspberry Pi® Hardware.

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

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

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

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

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

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.

Deploy an Edge detection function on the Raspberry Pi™ hardware as a stanalone executable using MATLAB® Support Package for Raspberry Pi Hardware. In this example, you will learn how to

You the how to deploy a MATLAB® function as a standalone executable on the Raspberry Pi™ Hardware using MATLAB Support Package for Raspberry Pi Hardware.

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.

The ibcso function plots International Bathymetric Chart of the Southern Ocean (IBCSO) digital bathymetric model dat using using Antarctic Mapping Tools. IBCSO data are described in full

Stipple creates a hatch filling or stippling within a grid. This function is designed primarily to show regions of statistical significance in spatial maps.

The ibcso_interp function interpolates bed elevations from the International Bathymetric Chart of the Southern Ocean (IBCSO) digital bathymetric model. IBCSO data are described in full

StoichTools comprises a set of Matlab functions for doing stoichiometric analysis. These functions parse standard chemical notation for a variety of stoichiometric calculations

The ibcso_data function returns IBCSO bathymetric data and corresponding geographic or polar stereographic cartesian coordinates. IBCSO data are described in full on the IBCSO website

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

Besselzero calculates the zeros of Bessel function of the first and second kind

Sinefit fits a least-squares estimate of a sinusoid to time series data that have a periodicity of 1 year.

Sinefit_bootstrap performs a bootstrap analysis on the parameters estimated by the function sinefit. Bootstrapping means applying the sinefit function to a bunch of subsamples of the

Sineval produces a sinusoid of specified amplitude and phase with a frequency of 1/yr.

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

Author: Tobias Neuhauser

This toolbox provides a set of Simulink virtual environments to aid in robotics educations. Users can interact directly with robots via actuator and sensor blocks to learn to program robots

How to create a histogram plot in MATLAB®.

The wind field is now simulated along a vertical line (e.g. a wind mast). I use the input file INPUT_MAST.txt with 20 nodes created along a vertical line, for altitudes ranging from 10 to 90 m.

How to create a polar plot in MATLAB®.

The wind field is now simulated on a circle defined in the vertical plane (yz) normal to the flow. The function windSim2 is therefore used with two input files:

Set the motor voltages to have the robot move forward

Load Monthly Climatic Data of the World dataset from Berkeley Earth and plot the average temperature computed on the available dataset for the 12 months of the year.

How to create a 3D plot in MATLAB®.

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