MATLAB Examples

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

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.

All the scripts provided are used in Partial Differential Equation Methods for Image Inpainting (Carola-Bibiane Schoenlieb, Cambridge University Press, 2015):

This example was authored by the MathWorks community.

This script reads in an image file and then attempts to find a green object in the image. It is designed to find one green ball and highlight that ball on the original image

(c) Viktor Witkovsky (witkovsky@savba.sk) Ver.: 31-Jul-2014 18:27:32

How many of you have successfully solved a Rubik's Cube® before? How long did you take to solve a cube that your friend scrambled? I have been able to successfully solve a Rubik's Cube, but have

The Fibonacci numbers are an easily accessible area in number theory. As well, they appear in many places in mathematics and in nature , look here too . For those interested in reading more

Copyright (c) 2008 Gabriel Peyre

Utility from File Exchange

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

Test the use of Forward-backward-like splitting for the resolution of a compressed sensing regularization.

This script demonstrates testing a simple technical indicator strategy and backtesting to optimize its parameters

This demo file teaches about the aliquot parts of a number, and how to use the functions I've provided.

Spl returns sound pressure level in decibels for an input signal p_Pa in pascals. A reference pressure ref must be declared in units of pascals or specified as 'air' or 'water' to use standard

Model, configure, generate AUTOSAR compliant code and export xml files using Simulink® and Embedded Coder®. The Vehicle Speed and Odometer calculations example demonstrates this

These prototype MATLAB functions create and plot graphs from images based on neighbor relationships between pixels. You must have MATLAB R2015b to use them.

Backward-compatible with Optimization Toolbox version 1.0

Copyright 2017 The MathWorks, Inc.

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

F. Moisy, 28 april 2010.

Registers two images (2-D rigid translation) within a fraction of a pixel specified by the user. Instead of computing a zero-padded FFT (fast Fourier transform), this code uses selective

Test for DR algorithm for L1 minimization (BP). We do here a compressed sensing resolution (random matrix).

Test for Rudin-Osher-Fatemi denoising (ROF) using FB-like method.

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

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

This demo is an example of performing data mining on historical fuel economy data. We have data from various cars built from year 2000 up to 2012.

This is the fourth script of 4 in the Natural Gas Storage Valuation case study. In this script, we value the storage facility using the rolling intrinsic optimization method. To do so, we

In this demo, we use regression trees to predict the fuel economy of vehicles.

We will derive the equations of motion for an overhead gantry crane system. We simplify the gantry cane system as just a payload (pendulum) on a movable support, as illustrated in the diagram

Non-negative least-squares solves the following problem:

Mathematically, this is an example of the change of variable theorem for integrals of multidimensional functions [1].

David Young

Script to Run Gary Vanderplaats cantilever Beam with SQP and SLP. N beam segments and 2N design variables, taken from Vanderplaats (1984) Example 5-1, pp. 147-150.

This is the second script of 4 in the Natural Gas Storage Valuation case study. This script prices a natural gas storage contract using the Intrinsic & Spread Option valuation methods. Please

This is a simple example of how to fit data using the logistic function. For more information, please visit: http://en.wikipedia.org/wiki/Logistic_regression

Hock W., Schittkowski K. (1981): Test Examples for Nonlinear Programming Codes, Willi Hock, Klaus Schittkowski, Springer, Lecture Notes in Economics and Mathematical Systems, Vol. 187

Matlab_Abaqus_10_Bar_Truss is a Matlab source code which is used to find the optimum design of a 10-bar truss, described in section 2. It is developed by George Papazafeiropoulos

A MATLAB implementation of the Faddeev-Leverrier algorithm to compute the coefficients of the characteristic polynomial of a given matrix and to get the inverse of the matrix without extra

The script polyfit_roots_drv.m demonstrates the function polyfit_roots that finds the roots and the constant so that the polynomial

Script to Run Gary Vanderplaats cantilever Beam with slp_trust. N beam segments and 2N design variables, taken from Vanderplaats (1984) Example 5-1, pp. 147-150.

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

The notation followed here and in the following MATLAB codes:

Truth: 0

Matlab_Abaqus_25_Bar_Truss is a Matlab source code which is used to find the optimum design of a 25-bar truss, described in section 2. It is developed by George Papazafeiropoulos

Test for ADMM algorithm convergence on a randomized example.

The steps to accomplish to create a geometry in Blender to be used in Matlab with the geometry objects. Only the relevant steps for this task are explained here; the commands specific to

This is the code documented in the tutorial on Polynomials in MATLAB. (This published MATLAB code, only presents the code implementation. The PDF document on the tutorial also includes the

Haftka, R. T. and Z. Gurdal (1992), Elements of Structural Optimization, Kluwer Academic Publishers

Customer provided this example where he was puzzled why fmincon had a hard time finding the mimimum value.

Abstract:

Demonstrate ricernd, ricepdf, and ricestat, in the context of simulating Rician distributed noise for Magnetic Resonance Imaging magnitude data.

By F. Pedroche, M. Rebollo, C. Carrascosa and A. Palomares (2012) Universitat Politècnica de València (Spain)

(c) 2013 Matthew Harker and Paul O'Leary

Application where the grid where the values are known is a regular distribution of points.

This is the first script of 4 in the Natural Gas Storage Valuation case study. In this script, we import a data set of historical futures prices for natural gas, pre-process them and compute

The scope of these two functions is to organize a flat dataset into a PIVOT table (and eventually undo it). This guide will illustrate how to use them.

Mmx treats an N-D matrix of double precision values as a set of pages of 2D matrices, and performs various matrix operations on those pages. mmx uses multithreading over the higher dimensions

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}

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

1-D guaranteed function integration using trapezoidal rule

Regress_Bivariate:

This function processes absolute radiometric data (irradiance) with dimension and calculates:

Illustrates how to solve a second order differential equation using one of the numeric ODE solvers in MATLAB.

When the x-values are equally spaced, the derivatives at the interior points as calculated by DIFFXY are approximated in the same way as the native Matlab function GRADIENT, i.e. using the

Monte Carlo method to estimate the mean of a Bernoulli random variable to within a specified absolute error tolerance with guaranteed confidence level 1-alpha.

The second term

Copyright 2016 The MathWorks, Inc.

Richard Brown, May 28, 2007

Find the cross-sections of the members of the 10-bar truss so that its weight is minimized and the constraints are satisfied. For more information please see the Documentation of

Compute American option prices from characteristic function of asset return distribution. Part of the CFH Toolbox.

If carefully built, a sundial is perfectly capable of keeping accurate time. The problem is that you need a different sundial for every combination of latitude, longitude, and day of the

By Ken Deeley, MathWorks

Differintegral of the identity function using Fourier series representation

This is a geometry file to be used with AFP objects.

Resolution of multiphysic boundary value problem.

This MATLAB live script analyzes the dynamics of two bodies attracted by the force of gravity using Symbolic Math Toolbox, highlighting many of its key features.

Called functions explicitlly shown in this function body: denoised_unwrap, phase_wrap.

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,

This is an example where a grid of scattered points is to be written with a geometry. The geometry used comes from the example #1 of EABE_v34_p30. This set of points is used for the demo on

Monte Carlo method to estimate the mean of a random variable

Initialize a clean workspace. Save your work first!

Differintegral of a cubic polynomial using Fourier series representation

Plot function is optional argument first argument is a list of the population (columns are agents) second argument is a style for different phases: 'b.' for moving, 'r+' for cluster,'c*' for

Corrmap returns an (N-1)-dimensional array of correlation coefficients between y and A along dimension dim of A.

Find the cross-sections of the members of the 25-bar truss so that its weight is minimized and the constraints are satisfied. For more information please see the Documentation of

Application where the grid where the values are known is a scattered distribution of points. The geometry used comes from the example #1 of EABE_v34_p30. For the purposes of the example, the

Quasi-Monte Carlo method using Sobol' cubature over the d-dimensional region to integrate within a specified generalized error tolerance with guarantees under Walsh-Fourier

AOE 5064 Homework #3, Problem 5a: SQP for Svanberg beam

Batchpleas is a wrapper for lsqnonlin, allowing it to solve many small problems (all with the same parameterization) in one batched, partitioned nonlinear least squares estimation. This

Find all points on a gridded surface Z that are farther than some distance from an array of points given by (xpt,|ypt|), then replace the distant points in Z with NaN|s or some declared

When plotting some function, it is often desirable to cover the function domain uniformly. In this short document, somewhat different way to create almost equally-spaced values for

This should be zero. Ok, its a trivial test case.

The L8read function reads full-resolution Level 1 Landsat 8 images and has the ability to subset the image before loading.

Monte Carlo method to evaluate a multidimensional integral

1-D guaranteed locally adaptive function approximation (or function recovery) on [a,b]

Differintegral of a tabular function using Fourier series representation

This publishable m-file demonstrates fitcircle, a function for finding the best fit circle by least squares. The implementation is based on Least-Squares Fitting of Circles and Ellipses,

This data set represents uncertain measurements of the deflection of a doubly clamped beam. The aim is to fit a curve through the data which fulfille the theoritical known constraints

Note that x0 is actually ignored for the univariate optimizers fzero and fminbnd, as long as bounds are provided. Those bounds provide the information on where to search. Once the sample

Copyright 2015-2016 The MathWorks, Inc.Published with MATLAB® R2016a

As an inquisitive (and sometimes silly) college student, I would, at times, think of strange problems that have the potential for interesting solutions. On one such occasion, I was in the

This product allows users to interactively design a tabular expression. The resusulting function can be saved as a Simulink block or to a Matlab m-file. Tabular Expressions can be proved to

The Riemann problem of 1D elastodynamics

This (publishable) script nndemo.m demonstrates the features of the nearestneighbour function.

Parameters of the Riemann problem

Parameters of the fitted ellipse

Svanberg, Krister, "The Method of Moving Asymptotes--A New Method for Structural Optimization," Intl. J. Num. Meth. Vol. 24, 1987, pp. 359-373.

Constitutive law in 1D elastodynamics

Quasi-Monte Carlo method using rank-1 Lattices cubature over a d-dimensional region to integrate within a specified generalized error tolerance with guarantees under Fourier

We demonstrate routines of the PROMPT package by modeling conformational motion between two conformations of calmodulin. To launch the example, use the following command:

1-D guaranteed global minimum value on [a,b] and the subset containing optimal solutions

This function performs cumulative mathematics on 2D matrices at arbitrary angles. This function works by using the Image Processing Toolbox function imrotate to rotate an input matrix to

La Toolbox concernant le calcul symbolique dans Matlab est un outil très intéressant dans différents domaines de la physique en particulier. Pour illustrer son utilisation, nous allons

Introducing fplot for disco...

Example problem taken from Vanderplaats textbook, example 3-1. Unconstrained potential energy minimization of two springs. Complex-step gradient.

Computation of a limit usually involves a function that we cannot evaluate at the point of interest. It is often due to a singularity at the point of interest that we cannot evaluate the

Note that if we look at the points that are very close to z0, then the polynomial may have strange coefficients.

How might one best compute the limit of a function at a specific point using numerical techniques? Since we need to compute a limit, the function will generally be singular in some fashion at

First, run make.m to create mex files. NOTE: 1) refer to your Matlab on line help on how to configure mex and create mex file 2) LineTwoPnts.mexw32 and SegInMat.mexw32(matlabr2006a + win32)

This script demonstrates how to use the Optimization Toolbox to simulate electromagnetic shielding by a Faraday Cage .

Igor Podlubny (a), Tomas Skovranek (a), Blas M. Vinagre Jara (b)

This means no pennies. There are only 11 ways to do this.

The rocket trajectory consists of three phases - acceleration, uniform movement and deceleration.

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

Ema's stick man is tall and has a top hat. What a gentleman.

Constraints set

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

Jana's stickgirl is running full speed with headphones.

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

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

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

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

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

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

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

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

It is often useful to use a graphical format to view the distribution of the nonzero elements within a sparse matrix. The MATLAB spy function produces a template view of the sparsity

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

Three of the 19 ways to compute the exponential of a matrix.

Plot the imaginary part versus the real part of a complex vector, z . With complex inputs, plot(z) is equivalent to plot(real(z),imag(z)) , where real(z) is the real part of z and imag(z) is the

Use griddedInterpolant to resample the pixels in an image. Resampling an image is useful for adjusting the resolution and size, and you also can use it to smooth out the pixels after zooming.

Analyze and visualize earthquake data.

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

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

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

Use normalization to improve scattered data interpolation results with griddata . Normalization can improve the interpolation results in some cases, but in others it can compromise the

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

Perform arithmetic and linear algebra with single precision data. It also shows how the results are computed appropriately in single-precision or double-precision, depending on the

The convhull and convhulln functions take a set of points and output the indices of the points that lie on the boundary of the convex hull. The point index-based representation of the convex

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

Compute and represent the finite difference Laplacian on an L-shaped domain.

The use of the FFT function for spectral analysis. A common use of FFT's is to find the frequency components of a signal buried in a noisy time domain signal.

The optimal fitting of a nonlinear function to a set of data. It uses FMINSEARCH, an implementation of the Nelder-Mead simplex (direct search) algorithm, to minimize a nonlinear function of

Perform arithmetic on integer data representing signals and images.

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

Create, edit, and query Delaunay triangulations using the delaunayTriangulation class. The Delaunay triangulation is the most widely used triangulation in scientific computing. The

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

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

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

Use ODE23 and ODE45 on a simple differential equation. ODE23 and ODE45 are functions for the numerical solution of ordinary differential equations. They employ variable step size

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

Reduce the dimensionality of the grid plane arrays in 3-D to solve a 2-D interpolation problem.

The Voronoi diagram and the Delaunay triangulation on the same 2-D plot.

Using polynomials of even modest degree to predict the future by extrapolating data is a risky business.

Create a griddedInterpolant and how to use it effectively to perform grid-based interpolation.

The alpha shape of a set of points is a generalization of the convex hull and a subgraph of the Delaunay triangulation. That is, the convex hull is just one type of alpha shape, and the full family

This topic shows how to constrain the solution of an ODE to be nonnegative. Imposing nonnegativity is not always trivial, but sometimes it is necessary due to the physical interpretation of

Interpolate three 1-D data sets in a single pass using griddedInterpolant . This is a faster alternative to looping over your data sets.

An interesting graphical approach to find out whether e^pi is greater than pi^e or not.

An application of sparse matrices and explains the relationship between graphs and matrices.

(graphically) how the Fourier series expansion for a square wave is made up of a sum of odd harmonics.

Interpolate two different samplings of the same parabolic function. It also shows that a better distribution of sample points produces better extrapolation results.

The finite element mesh for a NASA airfoil, including two trailing flaps.

You can solve polynomial equations involving trigonometric functions by simplifying the equation using a substitution. The resulting polynomial of one variable no longer contains any

In optics, the Fourier transform can be used to describe the diffraction pattern produced by a plane wave incident on an optical mask with a small aperture [1]. This example uses the fft2

Represent a polynomial as a vector in MATLAB® and evaluate the polynomial at points of interest.

Extrapolate a well sampled 3-D gridded dataset using scatteredInterpolant . The query points lie on a planar grid that is completely outside domain.

Plot graphs, and then customize the display to add labels or highlighting to the graph nodes and edges.

Compute the convex hull of a 2-D point set using the alphaShape function.

Use the rng function, which provides control over random number generation.

Access and modify the nodes and/or edges in a graph or digraph object using the addedge , rmedge , addnode , rmnode , findedge , findnode , and subgraph functions.

Create and plot a 1-D interpolant using griddedInterpolant with a cubic interpolation method.

Formulate and solve three different types of differential equations using MATLAB®. MATLAB offers several numerical algorithms to solve a wide variety of differential equations.

The Delaunay triangulation is well suited to scattered data interpolation problems because it has favorable geometric properties that produce good results. These properties are:

The convex hull of a set of points in N-D space is the smallest convex region enclosing all points in the set. If you think of a 2-D set of points as pegs in a peg board, the convex hull of that set

Perform linear interpolation on a scattered set of points with a specific Delaunay triangulation.

The relationship between a Delaunay triangulation of a set of points in 2-D and the convex hull of that set of points.

The Fourier transform is a mathematical formula that relates a signal sampled in time or space to the same signal sampled in frequency. In signal processing, the Fourier transform can reveal

Approximate gradients of a function by finite differences. It then shows how to plot a tangent plane to a point on the surface by using these approximated gradients.

Use the fzero function to find the roots of a polynomial in a specific interval. Among other uses, this method is suitable if you plot the polynomial and want to know the value of a particular

Use a PageRank algorithm to rank a collection of websites. Although the PageRank algorithm was originally designed to rank search engine results, it also can be more broadly applied to the

Use the polyint and polyder functions to analytically integrate or differentiate any polynomial represented by a vector of coefficients.

Working with missing data is a common task in data preprocessing. Although sometimes missing values signify a meaningful event in the data, they often represent unreliable or unusable data

You can use the Fourier transform to analyze variations in data, such as an event in nature over a period time.

Use scatteredInterpolant to interpolate a scattered sampling of the peaks function.

Create and plot a 2-D interpolant using griddedInterpolant .

Create a 3-D interpolant and evaluate over a slice plane so you can plot the values on that plane.

Interpolate data with a cubic spline in 2 dimensions. It uses the MATLAB® SPLINE function. It does NOT use the Curve Fitting Toolbox™ spline functions, which are a complete set of functions

How reordering the rows and columns of a sparse matrix can influence the speed and storage requirements of a matrix operation.

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