MATLAB Examples

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.

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

This example was authored by the MathWorks community.

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

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

Copyright 2017 The MathWorks, Inc.

(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

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

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

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

Utility from File Exchange

Copyright (c) 2008 Gabriel Peyre

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

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.

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

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

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

F. Moisy, 28 april 2010.

Backward-compatible with Optimization Toolbox version 1.0

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

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

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

Non-negative least-squares solves the following problem:

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

Richard Brown, May 28, 2007

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

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

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

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.

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

David Young

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

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

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

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

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

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

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.

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

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.

(c) 2013 Matthew Harker and Paul O'Leary

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

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

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

This demo shows index replication where the goal is to find a portfolio of stocks that replicates performance of the entire S&P 500. The data used is S&P 500 returns from Aug 21, 2009 to Aug 20,

The notation followed here and in the following MATLAB codes:

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

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

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

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

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

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

Copyright 2016 The MathWorks, Inc.

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

Abstract:

Test for ADMM algorithm convergence on a randomized example.

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

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

Truth: 0

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.

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

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

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.

Regress_Bivariate:

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 a geometry file to be used with AFP objects.

The second term

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

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

By Ken Deeley, MathWorks

Differintegral of the identity function using Fourier series representation

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

Resolution of multiphysic boundary value problem.

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

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

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,

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

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

Initialize a clean workspace. Save your work first!

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

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

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

Introducing fplot for disco...

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

The Riemann problem of 1D elastodynamics

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

Differintegral of a cubic polynomial using Fourier series representation

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

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

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

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

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

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

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

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,

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

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

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

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

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

Differintegral of a tabular function using Fourier series representation

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

Parameters of the Riemann problem

Constitutive law in 1D elastodynamics

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

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

Program Apple iOS app with MATLAB language.

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

Parameters of the fitted ellipse

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

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

This live script reviews functions, function notation and necessary properties.

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

In this tutorial a simple uncertainty quantification of a mechanical model of a long bridge is presented.

This script runs the Cantilever Beam Tutorial in OpenCOSSAN. The documentation and the problem description of this example is available 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 .

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

In this tutorial the global sensitivity analysis is applied to a practical problem in structural engineering: a mechanical model of a long bridge.

Constraints set

Medical image segmentation using texture analysis

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

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

This toolbox provides a basic MATLAB interface to CVXOPT's cone LP solver.

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.

This live script covers the concept of derivatives and how to calculate them.

Jana's stickgirl is running full speed with headphones.

This live script covers the concepts of antiderivatives and integrals.

This live script covers the concept of limits, the main properties and techniques for calculating them.

Perform a reliability analysis on a cantilever beam. The documentation and the problem description of this example is available at:

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

This live script covers the concept of continuity using limits.

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

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

This tutotial shows how to use the SystemReliability object in COSSAN-X in order to estimate the failure probability of a parellel system. This tutorial is based on the example #5 (pag.271)

Add a description for your toolbox here.

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

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

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.

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

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 the Laplacian matrix of a graph to compute the Fiedler vector. The Fiedler vector can be used to partition the graph into two subgraphs.

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.

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

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.

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.

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.

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

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.

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.

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 the polyint and polyder functions to analytically integrate or differentiate any polynomial represented by a vector of coefficients.

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.

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

How the Fourier series expansion for a square wave is made up of a sum of odd harmonics.

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

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

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

Analyze and visualize earthquake data.

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

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

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

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

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.

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

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.

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

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

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

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

Perform arithmetic on integer data representing signals and images.

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

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

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

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

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

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

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