MATLAB Examples

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

Welcome to this MATLAB Video tutorial. If you have never used MATLAB before, this demonstration will get you started and show you where to go to next to learn more.

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,

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

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

Test for the good size of a matrix containing floats

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.

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.

This example was authored by the MathWorks community.

This live script covers the concepts of antiderivatives and integrals.

Introducing fplot for disco...

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.

Copyright 2017 The MathWorks, Inc.

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

Medical image segmentation using texture analysis

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

This tutorial shows how to perform a Reliability Based Optimization on a cantilever beam. The goal of this tutorial is to optimize a clamped beam under tip load considering uncertainties.

Perform optimization on the cantilever beam ( TutorialCantileverBeamMatlab.html ) using a MATLAB evaluator.

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

Use linear programming and mixed-integer linear programming techniques to determine which bonds should be purchased to cover a given a cash flow in order to meet payout obligations, say for

Now that we can generate a forecast for future electricity demand, the next question is what actions should we take based on that forecast? One area of interest is how to operate a combination

Abstract:

Beta is vector of regressors P(beta|D) ~ N(beta| mu, lambda) mu = lambda * X{transpose} * big_sigma^(-1) * Y lambda = (X{transpose} * inv(sigma) * X + inv(big_omega))^{-1}

Regress_Bivariate:

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,

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.

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.

How to create a rose plot in MATLAB®.

Flow cytometry is a method for quantitating components or structural features of cells primarily by optical means. Although it makes measurements on one cell at a time, it can process

How pcolor and surf offset data by one half pixel and discard one row and one column of data. This example shows the effect in pcolor, but the results will be the same with surf.

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

A few examples of 3-d image smoothing through multivrant kernel regression: ksrmv.

How to create an errorbar plot in MATLAB®.

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

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

How to create a polar plot from a function in MATLAB®.

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

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

From this post on the MATLAB Graphics blog .

This function provides an option between the legend and text or annotation commands for labeling data that you plot. Edward Tufte says that data shouldn't stray far from its label, because

This function creates a legend whose patch objects match the transparency (alpha values) of plotted patch objects. Syntax follows legend exactly. In fact, if you so desire, you could always

File describes how anyone, even you! can create a map of sea level rise using data from the University of Colorado's Sea Level Research Group.

How to create a surface plot in MATLAB®.

How to create a 2D quiver plot in MATLAB®.

How to display a simple image in MATLAB®.

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

The function LINDEX converts the subscript index output from MATLAB's inbuilt MIN and MAX functions into linear indices. The linear indices are such that when used on the same array that was

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

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

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

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

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

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.

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

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.

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

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

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

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

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

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.

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

Open the folder containing the current file

Open a MATLAB file

Example 1: addcd, show, reset

Open the current working directory

Go up one level

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

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

This script demonstrates the complete workflow for developing an embedded machine learning application,including acquiring the data, extracting features, exploring various

Author: Shujaat Khan, shujaat123@gmail.com

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

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

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

必要なToolbox:

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

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.

Original reference to the cell list algorithm: Heinz, T.N. & Hunenberger, P.H. "A fast pairlist-construction algorithm for molecular simulations under periodic boundary conditions." J

Tic

Atom=System;

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:

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