MATLAB Examples

Fit an exponential model to data using the fit function.

Fit and compare polynomials up to sixth degree using Curve Fitting Toolbox, fitting some census data. It also shows how to fit a single-term exponential equation and compare this to the

Use the fit function to fit polynomials to data. The steps fit and plot polynomial curves and a surface, specify fit options, return goodness of fit statistics, calculate predictions, and

Work with a curve fit.

Use the fit function to fit a Fourier model to data.

Compare the effects of excluding outliers and robust fitting. The example shows how to exclude outliers at an arbitrary distance greater than 1.5 standard deviations from the model. The

Fit a custom equation to census data, specifying bounds, coefficients, and a problem-dependent parameter.

Work with a surface fit.

Find the first and second derivatives of a fit, and the integral of the fit, at the predictor values.

Use the fit function to fit power series models to data.

Use the fit function to fit a Gaussian model to data.

Remove outliers when curve fitting programmatically, using the 'Exclude' name/value pair argument with the fit or fitoptions functions. You can plot excluded data by supplying an Exclude

Construct and work with the ppform of a spline in Curve Fitting Toolbox™.

Construct splines in various ways using the spline functions in Curve Fitting Toolbox™.

Construct and work with the B-form of a spline in Curve Fitting Toolbox™.

Select and optimize knots using the optknt and newknt commands from Curve Fitting Toolbox™.

Use Curve Fitting Toolbox™ to fit response surfaces to some anesthesia data to analyze drug interaction effects. Response surface models provide a good method for understanding the

Fit polynomials up to sixth degree to some census data using Curve Fitting Toolbox™. It also shows how to fit a single-term exponential equation and compare this to the polynomial models.

Use Curve Fitting Toolbox™ to fit a response surface to some automotive data to investigate fuel efficiency.

Use the spmak, spcrv, cscvn and rscvn commands from Curve Fitting Toolbox™ to construct spline curves in the plane. This includes plotting tangents and computing the area enclosed by a

Use the cscvn command from Curve Fitting Toolbox™ to construct cubic spline curves in two and three dimensions.

Use the spline commands in Curve Fitting Toolbox™ to fit tensor product splines to bivariate gridded data.

Use spline commands from Curve Fitting Toolbox™ solve a nonlinear ordinary differential equation (ODE).

Fit a function to data using lsqcurvefit together with MultiStart .

Find the minimum of Rastrigin's function restricted so the first component of x is an integer. The components of x are further restricted to be in the region 5 \pi\le x(1) \le 20\pi,\ -20\pi\le

Optimize using the particleswarm solver. The particle swarm algorithm moves a population of particles called a swarm toward a minimum of an objective function. The velocity of each

Use an output function for particleswarm. The output function plots the range that the particles occupy in each dimension.

Optimize using the particleswarm solver.

How @gacreationlinearfeasible, the default creation function for linearly constrained problems, creates a population for ga. The population is well-dispersed, and is biased to lie on

Solve a mixed integer engineering design problem using the Genetic Algorithm (ga) solver in Global Optimization Toolbox.

The use of a custom output function in the genetic algorithm solver ga. The custom output function performs the following tasks:

Minimize an objective function subject to nonlinear inequality constraints and bounds using the Genetic Algorithm.

Use the genetic algorithm to minimize a function using a custom data type. The genetic algorithm is customized to solve the traveling salesman problem.

Create and manage options for the genetic algorithm function ga using optimoptions in the Global Optimization Toolbox.

Use a hybrid scheme to optimize a function using the Genetic Algorithm and another optimization method. ga can reach the region near an optimum point relatively quickly, but it can take many

Create and minimize a fitness function using the Genetic Algorithm in the Global Optimization Toolbox.

Create and minimize an objective function using Simulated Annealing in the Global Optimization Toolbox.

Create and manage options for the simulated annealing function simulannealbnd using optimoptions in the Global Optimization Toolbox.

Use simulated annealing to minimize a function using a custom data type. Here simulated annealing is customized to solve the multiprocessor scheduling problem.

Use the functions GlobalSearch and MultiStart.

Find a minimum of a non-smooth objective function using the ga and patternsearch functions in the Global Optimization Toolbox. Traditional derivative-based optimization methods, like

Find a minimum of a stochastic objective function using patternsearch. It also shows how Optimization Toolbox™ solvers are not suitable for this type of problem. The example uses a simple

The importance of choosing an appropriate solver for optimization problems. It also shows that a single point of non-smoothness can cause problems for Optimization Toolbox™ solvers.

Visually how pattern search optimizes a function. The function is the height of the terrain near Mount Washington, as a function of the x-y location. In order to find the top of Mount

Minimize an objective function subject to nonlinear inequality constraints and bounds using pattern search.

Create and manage options for the pattern search function patternsearch using the optimoptions function in the Global Optimization Toolbox.

Create an optimal design for a polynomial model using Model-Based Calibration Toolbox™ command-line interface.

Use the command-line functionality to generate local designs at each global operating point. This particular example shows how you can produce local maps for a diesel engine calibration.

Create and apply constraints to a design using Model-Based Calibration Toolbox™ command-line interface.

Design an experiment for the gasoline case study problem using the command-line interface to Model-Based Calibration Toolbox™. The gasoline case study describes how to systematically

Load and modify data using Model-Based Calibration Toolbox™ command-line interface. Data can be loaded from files (Excel® files, MATLAB® files, text files) and from the MATLAB®

Automatically generate an mbcmodel project for the gasoline case study using the command-line tools in Model-Based Calibration Toolbox™ .

Use the Model-Based Calibration Toolbox™ command-line functionality for point-by-point engine modeling projects.

Illustrates how a self-organizing map neural network can cluster iris flowers into classes topologically, providing insight into the types of flowers and a useful tool for further

Demonstrates looking for patterns in gene expression profiles in baker's yeast using neural networks.

Neurons in a competitive layer learn to represent different regions of the input space where input vectors occur.

Neurons in a 2-D layer learn to represent different regions of the input space where input vectors occur. In addition, neighboring neurons learn to respond to similar inputs, thus the layer

As in one-dimensional problems, this self-organizing map will learn to represent different regions of the input space where input vectors occur. In this example, however, the neurons will

Illustrates how a pattern recognition neural network can classify wines by winery based on its chemical characteristics.

Illustrates how to train a neural network to perform simple character recognition.

Use Neural Network Toolbox™ autoencoders functionality for training a deep neural network to classify images of digits.

Illustrates using a neural network as a classifier to identify the sex of crabs from physical dimensions of the crab.

Demonstrates using a neural network to detect cancer from mass spectrometry data on protein profiles.

Illustrates how a NARX (Nonlinear AutoRegressive with eXternal input) neural network can model a magnet levitation dynamical system.

Illustrates how a function fitting neural network can estimate body fat percentage based on anatomical measurements.

Illustrates how to design a linear neuron to predict the next value in a time series given the last five values.

Illustrates how an adaptive linear layer can learn to predict the next value in a signal, given the current and last four values.

A 2-input hard limit neuron fails to properly classify 5 input vectors because they are linearly non-separable.

A 2-input hard limit neuron is trained to classify 5 input vectors into two categories.

A 2-input hard limit neuron is trained to classify 5 input vectors into two categories. Despite the fact that one input vector is much bigger than the others, training with LEARNPN is quick.

A 2-input hard limit neuron is trained to classify 5 input vectors into two categories. However, because 1 input vector is much larger than all of the others, training takes a long time.

Uses functions NEWPNN and SIM.

Uses the NEWRB function to create a radial basis network that approximates a function defined by a set of data points.

A radial basis network is trained to respond to specific inputs with target outputs. However, because the spread of the radial basis neurons is too high, each neuron responds essentially the

A radial basis network is trained to respond to specific inputs with target outputs. However, because the spread of the radial basis neurons is too low, the network requires many neurons.

Uses functions NEWGRNN and SIM.

Solve portfolio optimization problems using the interior-point quadratic programming algorithm in quadprog. The function quadprog belongs to Optimization Toolbox™.

Determine the shape of a circus tent by solving a large-scale quadratic optimization problem. The shape of a circus tent is determined by a constrained optimization problem. We will solve

The value of using sparse arithmetic when you have a sparse problem. The matrix has n rows, where you choose n to be a large value, and a few nonzero diagonal bands. A full matrix of size n -by- n can

Use binary integer programming to solve the classic traveling salesman problem. This problem involves finding the shortest closed tour (path) through a set of stops (cities). In this case

Set up and solve a mixed-integer linear programming problem. The problem is to find the optimal production and distribution levels among a set of factories, warehouses, and sales outlets.

Schedule two gas-fired electric generators optimally, meaning to get the most revenue minus cost. While the example is not entirely realistic, it does show how to take into account costs

Solve a Sudoku puzzle using binary integer programming. For the solver-based approach, see Solve Sudoku Puzzles Via Integer Programming: Solver-Based .

Solve a Mixed-Integer Quadratic Programming (MIQP) portfolio optimization problem using the problem-based approach. The idea is to iteratively solve a sequence of mixed-integer linear

Solve an assignment problem by binary integer programming using the optimization problem approach. For the solver-based approach, see Office Assignments by Binary Integer Programming:

Solve a cutting stock problem using linear programming with an integer linear programming subroutine. The example uses the problem-based approach. For the solver-based approach, see

How to speed up the minimization of an expensive optimization problem using functions in Optimization Toolbox™ and Global Optimization Toolbox. In the first part of the example we solve the

Use two nonlinear optimization solvers and how to set options. The nonlinear solvers that we use in this example are fminunc and fmincon .

Perform nonlinear fitting of complex-valued data. While most Optimization Toolbox™ solvers and algorithms operate only on real-valued data, least-squares solvers and fsolve can work on

Fit a nonlinear function to data using several Optimization Toolbox™ algorithms.

Recover a blurred image by solving a large-scale bound-constrained linear least-squares optimization problem.

Fit parameters of an ODE to data in two ways. The first shows a straightforward fit of a constant-speed circular path to a portion of a solution of the Lorenz system, a famous ODE with sensitive

Use the problem-based approach to solve an investment problem with deterministic returns over a fixed number of years T . The problem is to allocate your money over available investments to

Create a multiperiod inventory model in the problem-based framework. The problem is to schedule production of fertilizer blends over a period of time using a variety of ingredients whose

Solve a nonlinear filter design problem using a minimax optimization algorithm, fminimax , in Optimization Toolbox™. Note that to run this example you must have the Signal Processing

Solve a pole-placement problem using the multiobjective goal attainment method. This algorithm is implemented in the function fgoalattain .

Use the Symbolic Math Toolbox™ functions named jacobian and matlabFunction to provide derivatives to optimization solvers. Optimization Toolbox™ solvers are usually more accurate and

Minimize Rosenbrock's "banana function":

Use semi-infinite programming to investigate the effect of uncertainty in the model parameters of an optimization problem. We will formulate and solve an optimization problem using the

Solve Poisson's equation using the programmatic workflow. For the PDE Modeler app solution, see docid:pde_ug.bvhf75n . The problem formulation is - \Delta u = 1 in \Omega , u = 0 on \delta

Solve the heat equation with a source term using the Partial Differential Equation Toolbox™.

How a 3-D axisymmetric model can be analyzed using a 2-D model. The model geometry, material properties, and boundary conditions must all be symmetric about a single axis for this

Perform a heat transfer analysis of a thin plate using the Partial Differential Equation Toolbox™.

An idealized thermal analysis of a rectangular block with a rectangular cavity in the center. One of the purposes of this example is to show how temperature-dependent thermal conductivity

Perform a 3-D transient heat conduction analysis of a hollow sphere made of three different layers of material, subject to a nonuniform external heat flux.

Calculate the deflection of a structural plate acted on by a pressure loading using the Partial Differential Equation Toolbox™.

Solve a coupled elasticity-electrostatics problem using Partial Differential Equation Toolbox™. Piezoelectric materials deform when a voltage is applied. Conversely, a voltage is

Include damping in the transient analysis of a simple cantilever beam analyzed with the Partial Differential Equation Toolbox™. The beam is modeled with a plane stress elasticity

Analyze an idealized 3-D mechanical part under an applied load using Finite Element Analysis (FEA). The objective of the analysis is to determine the maximal deflection caused by the load.

Calculate the vibration modes and frequencies of a 3-D simply supported, square, elastic plate. The dimensions and material properties of the plate are taken from a standard finite element

The Partial Differential Equation Toolbox™ analysis of the dynamic behavior of a beam clamped at both ends and loaded with a uniform pressure load. The pressure load is suddenly applied at

Perform modal and transient analysis of a tuning fork.

Perform a 2-D plane-stress elasticity analysis.

Create contour slices in various directions through a solution in 3-D geometry.

Solves a Poisson's equation with a delta-function point source on the unit disk using the adaptmesh function in the Partial Differential Equation Toolbox™.

Numerically solve a Poisson's equation using the solvepde function in Partial Differential Equation Toolbox™.

Solve the wave equation using the solvepde function in the Partial Differential Equation Toolbox™.

Solve a Helmholtz equation using the solvepde function in Partial Differential Toolbox™.

Solve a nonlinear elliptic problem.

Perform one-level domain decomposition for complicated geometries, where you can decompose this geometry into the union of more subdomains of simpler structure. Such structures are

Calculate eigenvalues and eigenvectors using the programmatic workflow. For the PDE Modeler app solution, see Eigenvalues and Eigenmodes of the L-Shaped Membrane: PDE App .

Compute the eigenvalues and eigenmodes of a square domain using the programmatic workflow. For the PDE Modeler app solution, see Eigenvalues and Eigenmodes of a Square .

Use anovan to fit models where a factor's levels represent a random selection from a larger (infinite) set of possible levels.

In this example, use a database of 1985 car imports with 205 observations, 25 predictors, and 1 response, which is insurance risk rating, or "symboling." The first 15 variables are numeric

Generate a nonlinear classifier with Gaussian kernel function. First, generate one class of points inside the unit disk in two dimensions, and another class of points in the annulus from

Compute and plot the pdf of a Poisson distribution with parameter lambda = 5 .

Use Cook's Distance to determine the outliers in the data.

Perform linear and quadratic classification of Fisher iris data.

Use copulafit to calibrate copulas with data. To generate data Xsim with a distribution "just like" (in terms of marginal distributions and correlations) the distribution of data in the

Similar to the bootstrap is the jackknife, which uses resampling to estimate the bias of a sample statistic. Sometimes it is also used to estimate standard error of the sample statistic. The

Find the indices of the three nearest observations in X to each observation in Y with respect to the chi-square distance. This distance metric is used in correspondence analysis,

Perform N-way ANOVA on car data with mileage and other information on 406 cars made between 1970 and 1982.

Plot the pdf of a bivariate Student's t distribution. You can use this distribution for a higher number of dimensions as well, although visualization is not easy.

Create a classification tree ensemble for the ionosphere data set, and use it to predict the classification of a radar return with average measurements.

Compute and plot the pdf using four different values for the parameter r , the desired number of successes: .1 , 1 , 3 , and 6 . In each case, the probability of success p is .5 .

Use a random subspace ensemble to increase the accuracy of classification. It also shows how to use cross validation to determine good parameters for both the weak learner template and the

As for all discrete distributions, the cdf is a step function. The plot shows the discrete uniform cdf for N = 10.

You can also use ensembles of decision trees for classification. For this example, use ionosphere data with 351 observations and 34 real-valued predictors. The response variable is

Test for the significance of the regression coefficients using t-statistic.

Use cmdscale to perform classical (metric) multidimensional scaling, also known as principal coordinates analysis.

When you have missing data, trees and ensembles of trees give better predictions when they include surrogate splits. Furthermore, estimates of predictor importance are often different

Compute and plot the pdf of a multivariate normal distribution.

Load the sample data.

Display R-squared (coefficient of determination) and adjusted R-squared. Load the sample data and define the response and independent variables.

The bootstrap procedure involves choosing random samples with replacement from a data set and analyzing each sample the same way. Sampling with replacement means that each observation is

Use functional derivatives in the Symbolic Math Toolbox™ using the example of the wave equation. The wave equation for a string fixed at its ends is solved using functional derivatives. A

Do rotations and transforms in 3D using Symbolic Math Toolbox™ and matrices.

Perform simple matrix computations using Symbolic Math Toolbox™.

Compute the inverse of a Hilbert matrix using Symbolic Math Toolbox™.

Solve the eigenvalue problem of the Laplace operator on an L-shaped region.

Derive the symbolic stationary distribution of a trivial Markov chain by computing its eigen decomposition.

Work with large integers and their decimal representation using the Symbolic Math Toolbox™.

Use variable-precision arithmetic to investigate the decimal digits of pi using Symbolic Math Toolbox™.

Use variable-precision arithmetic to obtain high precision computations using Symbolic Math Toolbox™.

Get precise values for binomial coefficients and find probabilities in coin-tossing experiments using the Symbolic Math Toolbox.

Use some elementary functions on sym objects using the Symbolic Math Toolbox™.

Extracts closed-form solutions for the coefficients of frequencies in an output signal. The output signal results from passing an input through an analytical nonlinear transfer

Finds the average radiation power of two attracting charges moving in an elliptical orbit (an electric dipole ).

Develops a mathematical model using the Symbolic Math Toolbox to undistort an image and features a local function in the live script.

Uses Symbolic Math Toolbox and the Statistics and Machine Learning Toolbox to explore and derive a parametric analytical expression for the average power generated by a wind turbine.

Obtains the partial differential equation that describes the expected final price of an asset whose price is a stochastic process given by a stochastic differential equation.

Use a Padé approximant in control system theory to model time delays in the response of a first-order system.

Explores basic arbitrage concepts in a single-period, two-state asset portfolio. The portfolio consists of a bond, a long stock, and a long call option on the stock.

Use the Symbolic Math Toolbox™ functions jacobian and matlabFunction to provide analytical derivatives to optimization solvers. Optimization Toolbox™ solvers are usually more

Finds parameterized analytical expressions to model the displacement of a joint for a trivial cantilever truss structure in both static and frequency domains for use in Simscape.

Demonstrates that the Symbolic Math Toolbox helps minimize errors when solving a nonlinear system of equations.

Create a custom equation based components for the Simscape Library using the Symbolic Math Toolbox.

Model a bouncing ball, which is a classical hybrid dynamic system. This model includes both continuous dynamics and discrete transitions. It uses the Symbolic Math Toolbox to help explain

Classify text descriptions of weather reports using a deep learning long short-term memory (LSTM) network.

Analyze text using n-gram frequency counts.

Use the Latent Dirichlet Allocation (LDA) topic model to analyze text data.

Create a function which cleans and preprocesses text data for analysis.

Train a simple text classifier on word frequency counts using a bag-of-words model.

Visualize text data using word clouds.

Visualize word embeddings using 2-D and 3-D t-SNE and text scatter plots.

Extract the text data from text, HTML, Microsoft® Word, PDF, CSV, and Microsoft Excel® files and import it into MATLAB for analysis.

Decide on a suitable number of topics for a latent Dirichlet allocation (LDA) model.

Compare latent Dirichlet allocation (LDA) solvers by comparing the goodness of fit and the time taken to fit the model.

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