MATLAB Examples

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

How to create subplots in MATLAB®.

How to create wind flow visualization in MATLAB®.

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

Set the random number generator.

This example was authored by the MathWorks community.

The legappend function adds new entries to a legend. This is good for making PowerPoint slides, when you may want to start by plotting a few data sets, then add data to your plot one entry at a

This is a demonstration of using the topoplot_connect.m function. This function is only slightly modified from the original topoplot.m function which is part of EEGLAB. I have used EEGLAB

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)

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

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.

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

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

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

This function creates a title centered at the top of a figure. This may be used to add a title to a figure with several subplots.

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

Use array indexing to rasterize text into an existing image.

How to create a surface plot in MATLAB®.

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

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

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 visualize vector fields with streamlines in MATLAB®. Vector fields contain vector information for every point in space. For example, air flow data inside a wind tunnel is a vector

How to create a 3D bar chart in MATLAB®.

This function plots a 3D data volume as color-scaled semitransparent surface planes in each dimension.

Scattered data consists of a set of points X and corresponding values V, where the points have no structure or order between their relative locations. There are various approaches to

How to create a histogram plot in MATLAB®.

This function plots circles.

Pressure-Enthalpy Diagram

How to create a 3D plot in MATLAB®.

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

A number of people have asked me whether MATLAB can add text to heatmaps to show the exact values. This is very easy to do, however, making a the text robust to resizing, zooming and other

Using Bessel function of the first kind

How to add LaTeX equations to plots in MATLAB®.

In this example, a 2-dimensional random point set is given, which has an internal cavity. The idea for the concave mesh creation is to create initially the Delaunay triangulation of the point

In this example, two 2-dimensional random point sets are given. The basic problem of finding the intersection of the two point sets is addressed here. To answer this, the points of both point

How to create an area plot in MATLAB®.

Several examples show how to use the gkdeb2 function.

In this section theoretical details about convex hulls, Delaunay triangulations and Voronoi Diagrams, as well as their implementation in this package are presented.

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.

In this example, two 3-dimensional random point sets are given. The basic problem of finding the intersection of the two point sets is addressed here. To answer this, the points of both point

How to create an errorbar plot in MATLAB®.

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

This script demonstrates how approximately realistic-looking terrain can be generated with some very simple algorithms. These algorithms are interesting in their simplicity and their

How to create a y-axis semilog plot in MATLAB®.

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

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

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 3D mesh plot in MATLAB®.

An animated earth and moon.

How to add text to a plot in MATLAB®.

How to create a contour plot in MATLAB®.

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 toggles the rendering method used for screen and printing.

How to create an line plot with legend in MATLAB®.

This function computes the numerical solution of the Mackey-Glass delayed differential equation using the 4-th order Runge-Kutta method

In this example, a 2-dimensional point set is given, which has an internal cavity. The points form a uniform grid. The idea for the concave mesh creation is to create initially the Delaunay

A convex polytope P can be specified in two ways:

How to customize a plot to make them publication quality in MATLAB®.

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

In this example, a 2-dimensional gridded 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)

How to create a surface contour plot in MATLAB®.

By Bill McKeeman

How to create a polar plot in MATLAB®.

This function creates color maps from a list of any number of colors, given by their common names. Use of this function requires the rgb function which is available on File Exchange here. Color

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

This program has the ability to embed/hide multiple text images in any color image. The encoded text images can be seamlessly recoverable. The key advantage in this coding algorithm is, the

How to create a plot with two y axes in MATLAB®.

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

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

This function creates a flattened image with overlayed mask (with transparency). The mask is applied with a specified color and transparency over the original image, and the resulting

How to create a simple stem plot in MATLAB®.

Creating a chart of built-in colormaps in MATLAB®.

How to display multiple images in a subplot in MATLAB®.

How to create a vertical bar chart in MATLAB®.

There exist only 13 manners to split a cube in tetrahedras built exclusively with the 8 corners of the cube without counting simple rotations und reflections of the splittings. There are 12

These are some examples plots made with the carpetplot class.

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

How to create a rose plot in MATLAB®.

These functions create horizontal or vertical shaded regions on a plot. The syntax for both functions is the same.

How to create filled polygons on a plot in MATLAB®.

This problem is an example of application using the NumSim simulation program to solve the direct and inverse problems of acousto-electric conductivity modulation imaging.

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

A Torus is a geometric surface that can be represented by a doughnut: from any point on the surface, moving up/down or left/right will eventually lead you back to where you started, to continue

In this example the convex hull of a relatively large point set is calculated. For this purpose, the initial point set is divided into smaller point sets. The convex hull of each point set is

How to display a simple image in MATLAB®.

This function temporarily prints z values corresponding to clicked points on a surface or image. If multiple surfaces or images exist in the same axes, clickz first looks for surfaces and

Linearity in gray is important for a colormap to look reasonable when printed in grayscale ("black and white"), but note that precise linearity depends on the particular (non-unique)

How to produce a uniform lighting across the surfaces in MATLAB®. This lighting is good for viewing faceted surfaces.

This demonstrates some of the possabilities of generating combined vector and bitmap eps files from asingle figure. This is helpfull when large surface data is being generated which leads

Let's start by creating a mountain for our plane to fly by. We'll use Matlab's built-in peaks data for this, and we'll tweak the data set a little bit to set negative elevations to zero and

How to create a log-log plot in MATLAB®.

Post-glacial rebound (also known as glacial isostatic adjustment or GIA) describes the elastic relaxation of land masses that has been occurring since the weight of continental ice sheets

- 2)Adding A value Boundry To The Extra Grid Points - Using Mosaic Grid Points Value Boundry

How to add lines to a plot in MATLAB®.

Creating area charts, bar charts, and pie charts with some annotation in MATLAB®.

How to create an line plot in MATLAB®.

How to create a stacked bar chart in MATLAB®.

How to create an x-axis semilog plot in MATLAB®.

This makeAbsird function interprates the input data as a height-map and converts it to a random dot autostereogram. A random dot autosterogram is an image that can be percieved as

The point-in-polygon (PIP) problem asks whether each point of an arbitrary point set (query points) lies inside, outside, or on the boundary of the convex hull of another given point set

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

Having bins smaller than one pixel on the screen is strongly advized against because then data will randomly not be shown.

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

How to create a graph plot in MATLAB®.

The author - Eduard Polityko, PHD. Edition 16-Apr-2007

How to add a vertical colorbar to a plot in MATLAB®.

The point-in-polyhedron (PIP) problem asks whether each point of an arbitrary point set (query points) lies inside, outside, or on the boundary of the convex hull of another given point set

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

How to create an exploded pie chart in MATLAB®.

The Dragon Curve is a fractal that was made famous in Jurassic Park, a novel by Michael Crichton.

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

The cyclic polytope may be defined as the convex hull of vertices on the moment curve . The precise choice of which points on this curve are selected is irrelevant for the combinatorial

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

How to create a stem plot with multiple data in MATLAB®.

How to create a 3D pie chart in MATLAB®.

In this example, two 4-dimensional random point sets are given. The basic problem of finding the intersection of the two point sets is addressed here. To answer this, the points of both point

How to change color shading style for surface and patch objects in MATLAB®.

The nantight function sets axis limits to the range of finite data. (2D plots only.) This is similar to the command axis tight; however, nantight only considers the extent of finite data.

This script generates a Mackey-Glass time series using the 4th order Runge-Kutta method. The code is a straighforward translation in Matlab of C source code provided by Roger Jang, which is

How to create a simple pie chart in MATLAB®.

How to create a triangular plot in MATLAB®.

How to create an line plot with markers in MATLAB®.

From this post on the MATLAB Graphics blog .

How to create two overlapping waves in 3 dimension in MATLAB®.

How to create a horizontal bar chart in MATLAB®.

How to create a stair-step plot in MATLAB®.

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

How to create an line plot from a function in MATLAB®.

This function returns dx/dt of Mackey-Glass delayed differential equation

How to add a horizontal colorbar to a plot in MATLAB®.

From this post on the MATLAB Graphics blog

This Live Script performs a stress analysis of an aircraft wing and visualizes the results. It relies on a 3D CAD model of an aircraft wing, the analytically-derived wing load profile found in

We will develop and document an analytical model of the loads on the wing of a small passenger aircraft. Using the MATLAB Live Editor we can incorporate math equations, descriptive text, and

Description goes here

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

How to create a 3D line plot from a function in MATLAB®.

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

Convert between video files and sequences of image files using VideoReader and VideoWriter.

Heatmaps are a way to visualize data using color. This example shows how to import a file into MATLAB® as a table and create a heatmap from the table columns. It also shows how to modify the

Use animatedline to create an animation of a line that gets longer in every frame.

Use histogram to effectively view categorical data. You can use the name-value pairs 'NumDisplayBins', 'DisplayOrder', and 'ShowOthers' to change the display of a categorical

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

Geographic bubble charts are a way to visualize data overlaid on a map. For data with geographic characteristics, these charts can provide much-needed context. In this example, you import a

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

The plot box aspect ratio is the relative lengths of the x -axis, y -axis, and z -axis. By default, the plot box aspect ratio is based on the size of the figure. You can change the aspect ratio using

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.

You can use graphics functions in MATLAB to modify tick labels on Cartesian and polar plots.

Display mathematical expressions in your MATLAB® plots.

Change the colors used in a filled contour plot.

Create, display, and modify polar axes in MATLAB®.

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.

Get properties of an axes in MATLAB® and change axes property values to customize your graph.

Create and display the MATLAB® logo.

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.

Several techniques to visualize four dimensional (4-D) data in MATLAB®.

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 minumum and maximum data values by setting the

Get properties of a surface plot in MATLAB® and change the property values to customize your plot.

Modify properties of a chart with two y -axes by setting ruler properties.

Rotate a surface about the y -axis.

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

You can combine plots in several ways. Combine plots in the same axes, or create multiple axes in a figure.

Combine a contour plot and a quiver plot using the hold function.

Combine a line chart and a bar chart using two different y -axes. It also shows how to customize the line and bars.

Display an image using the default coordinate system. Use colors from the colorcube map.

Plot multiple lines and specify the associated legend labels during the plotting command.

Create a semitransparent bar chart by setting the FaceAlpha property of the bar series object to a value between 0 and 1. Display the grid lines.

Combine a line plot and two stem plots. Then, it shows how to add a title, axis labels, and a legend.

Display multiple plots in a single figure in MATLAB® by using subplot .

Create, display, and modify graphics objects in MATLAB®.

You can modify certain aspects of polar axes in order to make the chart more readable. For example, you can change the grid line locations and associated labels. You also can change the grid

Create a variety of 3-D plots in MATLAB®.

Change the location of an axis in MATLAB® to customize your graph. By adjusting the location of an axis, you can display axis lines through the origin.

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

Display text outside an axes by creating a second axes for the text. MATLAB® always displays text objects within an axes. If you want to place a text description alongside an axes, then you must

Plot a line using the patch function. Set the last entry of y to NaN so that patch creates a line instead of a closed polygon.

Customizing the tick values and labels along an axis can help highlight particular aspects of your data. These examples show some common customizations, such as modifying the tick value

You can control where data appears in the axes by setting the x -axis, y -axis, and z -axis limits. You also can change where the x -axis and y -axis lines appear (2-D plots only) or reverse the

Several ways to represent the Earth's topography. The data used in this example are available from the National Geophysical Data Center, NOAA US Department of Commerce under data

Display an image and convert it to grayscale in MATLAB®.

Adjust the color scale of a bivariate histogram plot to reveal additional details about the bins.

Trace a marker along a line by updating the data properties of the marker.

Create a simple line graph. Use the linspace function to define x as a vector of 100 linearly spaced values between 0 and 2\pi .

Combine two semitransparent area charts by setting the FaceAlpha and EdgeAlpha properties for each area object.

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

Use colormaps in MATLAB®.

Add text descriptions with arrows that point to three data points on a graph.

Modify properties of the baseline of a bar graph.

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

Several methods for visualizing volume data in MATLAB®.

Create a variety of 2-D plots in MATLAB®.

When using the default value of C=Z , the colors vary with changes in Z .

Animate a surface. Specifically, this example animates a spherical harmonic. Spherical harmonics are spherical versions of Fourier series and can be used to model the free oscillations of

Specify the colors for a chart with two y -axes by changing the default axes color order.

Create complex visualizations using multiple chart types or using overlays of the same chart type.

Create and customize plots with two y -axes.

Create a simple line plot and add a title to the graph. Include the Greek letter \pi in the title by using the TeX markup \pi .

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

Overlay two bar graphs and specify the bar colors and widths. Then, it shows how to add a legend, display the grid lines, and specify the tick labels.

The data aspect ratio is the relative length of the data units along the x -axis, y -axis, and z -axis. You can change the aspect ratio using the daspect function. Set the ratio as a three-element

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.

Modify properties of a chart with two y -axes by setting Axes properties.

Create a pie graph and automatically offset the pie slice with the greatest contribution.

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

Colorbars allow you to see the relationship between your data and the colors displayed in your chart. After you have created a colorbar, you can customize different aspects of its

How MATLAB® uses clipping in plots and how to control clipping.

Create and display a complex three dimensional object and control its appearance.

Visualize categorical data. The categorical array is used to store data with values from a finite set of discrete categories. A subset of charting types support categorical arrays.

Create a surface and vary the transparency based on the gradient of the z data. Use a flat transparency across each surface face by setting the FaceAlpha to 'flat' . Set the surface color to blue

Use annotations to add additional information to MATLAB® plots.

MATLAB® uses a default color scheme when it displays visualizations such as surface plots. You can change the color scheme by specifying a colormap. For example, here is a surface plot with

Plot several lines and create a legend that includes descriptions for a subset of the lines.

Change the data aspect ratio. Then revert back to the default plot box and data aspect ratios using the axis normal command.

Compare two data sets by overlaying their area graphs.

Add grid lines to a graph. It also describes how to edit the placement of the grid lines and modify their appearance.

Specify the line styles and line colors for a plot.

Bar graphs are useful for viewing results over a period of time, comparing results from different data sets, and showing how individual elements contribute to an aggregate amount.

These examples show how to create line plots, scatter plots, and histograms in polar coordinates. They also show how to annotate and change axes limits on polar plots.

Get properties of a ruler in MATLAB® and change ruler property values to customize an individual axis in your plot.

Plot data in polar coordinates. It also shows how to specify the angles at which to draw grid lines and how to specify the labels.

Create a chart with y -axes on the left and right sides using the yyaxis function. It also shows how to label each axis, combine multiple plots, and clear the plots associated with one or both of

Overlay a line plot on a stairstep plot.

Use graphics and font smoothing in MATLAB plots.

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

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

Display the path of a projectile as a function of time using a three-dimensional quiver plot.

Create mathematical symbols and special characters for plots and user interfaces using Unicode characters.

Get properties of a line in MATLAB® and change line property values to customize your plot.

Get properties of text in MATLAB® and change text property values to customize your plot.

Modify transparency of images, patches and surfaces.

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