matlab fundamentals

Download MATLAB Fundamentals

If you can't read please download the document

Upload: vincent-isoz

Post on 08-Apr-2016

548 views

Category:

Documents


8 download

DESCRIPTION

Course Notes for MATLAB

TRANSCRIPT

  • Cookbook (M 2)

    2014 -10 -18 (V0.7 Revision 98 ) , {oUUID 1.858}

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 2

    TABLE OF CONTENTS .................................................................................... 2

    TABLES INDEX ............................................................................................... 13

    Introduction ....................................................................................................... 14 MATLAB Evolution ................................................................................................. 15

    About the writer ................................................................................................ 20 ISOZ Vincent ............................................................................................................ 20

    KOLANI Daname ..................................................................................................... 21

    Warning .............................................................................................................. 22

    Your Opinion Matters! ..................................................................................... 23

    Useful Links ....................................................................................................... 24 General ...................................................................................................................... 24

    Forums ....................................................................................................................... 25

    Non-Mathworks additional powerful Toolboxes and tools ...................................... 25

    Bibliography ....................................................................................................... 26

    MATLAB core (without Toolbox) ................................................................... 27 New main core features (to be complete) ................................................................. 27

    MATLAB 2014a (8.3) ...................................................................................................... 27

    MATLAB 2013b (8.2) ..................................................................................................... 27 MATLAB 2013a (8.1) ...................................................................................................... 27

    MATLAB 2012b (8.0) ..................................................................................................... 27 MATLAB 2012a (7.14) .................................................................................................... 27 MATLAB 2011b (7.14) ................................................................................................... 28

    MATLAB 2011a (7.12) .................................................................................................... 28

    MATLAB 2010b (7.11) ................................................................................................... 28 MATLAB 2010a (7.10/2010) .......................................................................................... 28 MATLAB 2009b (7.9/2009) ............................................................................................ 28

    MATLAB 2009a (7.9/2009) ............................................................................................ 29 MATLAB 2008b (7.8/2009) ............................................................................................ 29 MATLAB 2008a (7.6/2008) ............................................................................................ 29

    MATLAB 2007b (7.5/2007) ............................................................................................ 29 MATLAB 2007a (7.4/2007) ............................................................................................ 30 MATLAB 2006b (7.3/2006) ............................................................................................ 30 MATLAB R14SP3 (7.1/2005) ......................................................................................... 31 MATLAB R14SP2 (7.0.4/2005) ...................................................................................... 31

    MATLAB R14SP1 (7.0.1/2004) ...................................................................................... 31

    MATLAB R14 (7.0/2004) ................................................................................................ 31

    MATLAB R13 (6.5/2000) ................................................................................................ 32 MATLAB R10 (5.2/1998) ................................................................................................ 32

    MATLAB R9 (5.1/1997) .................................................................................................. 32 MATLAB R8 (5.0/1996) .................................................................................................. 32

    Cite MATLAB .......................................................................................................... 33

    User Interface ............................................................................................................ 33

    Use Help .................................................................................................................... 46

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 3

    Edit a native function source code (if available) .............................................................. 48

    Most asked user preferences ..................................................................................... 50

    General commands .................................................................................................... 52 Execute system commands ............................................................................................... 52

    Call R from MATLAB ..............................................................................................................................53 Get MATLAB system information .................................................................................. 55 Some dates stuff ............................................................................................................... 60

    Manage variables .............................................................................................................. 61 Some Command Window controls .................................................................................. 63 Use the startup.m file ....................................................................................................... 65 Use the clipboard .............................................................................................................. 69

    Comments and multiple line commands ................................................................... 69

    Save workspace/Use commands diary ...................................................................... 70

    Arithmetic operations on scalars ............................................................................... 73

    Operators of comparison ........................................................................................... 76

    Real numbers manipulations ..................................................................................... 78 Command Windows real numbers formatting and output ............................................... 80

    Arithmetic operations on complex numbers ............................................................. 83 Identify the number type .................................................................................................. 86

    Rounding results ........................................................................................................ 88

    Set (vectors) operations ............................................................................................. 89 Important practical cases .................................................................................................. 96

    Counting/Removing NaN in cell arrays .....................................................................................................96 Counting/Removing NaN in (numeric) vectors .........................................................................................97 Finding the closest number in an vector ....................................................................................................98

    Arithmetic operations and manipulations of vectors ................................................ 99 Important practical cases ................................................................................................ 108

    Build an orthonormal vector base ............................................................................................................108

    Arithmetic operations and manipulations of matrices ............................................ 110 Important practical cases ................................................................................................ 125

    Removing NaN in matrices (arrays) ........................................................................................................125 Sampling matrix columns ........................................................................................................................126

    Creation multiple dimensional matrices .................................................................. 127

    Manipulating tables (structure array) ...................................................................... 128

    Mathematical functions ........................................................................................... 134

    Core (elementary) statistical functions .................................................................... 147

    Generate random variable ....................................................................................... 157

    Use of constants (permanent variables) .................................................................. 161

    Working with strings ............................................................................................... 164

    Working with dates ................................................................................................. 171 Important practical cases ................................................................................................ 178

    Convert year/month/day matrix as dates ..................................................................................................178 Difference in milliseconds/seconds between 2 dates ...............................................................................179

    Simple user interactions .......................................................................................... 182 Message boxes ................................................................................................................ 182 Input ............................................................................................................................... 183

    Input Dialog .................................................................................................................... 184 UI set color ..................................................................................................................... 187 UI save ............................................................................................................................ 188

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 4

    UI open ........................................................................................................................... 188

    UI get dir ........................................................................................................................ 190 Wait bar .......................................................................................................................... 192 Question dialog .............................................................................................................. 195 Menu ............................................................................................................................... 196 List dialog ....................................................................................................................... 198

    Send E-mail .................................................................................................................... 199

    Data management .................................................................................................... 200 MATLAB files (*.mat and *.m) ..................................................................................... 200 Manage working paths ................................................................................................... 203 Browse and manage folders and files ............................................................................. 209 Import/Export csv files ................................................................................................... 216

    Import very clean local csv files (with comas, without headers, without texts, without dates) ................216 Import clean local csv files (with semi-colons, with headers, without text, without dates) ......................219 Import local csv files (with semi-colons, with headers, with text, with dates) .........................................220 Merge csv files ........................................................................................................................................223 Import web csv files (with semi-colons, with headers, with text, with dates) .........................................225 Import from Yahoo Finance ....................................................................................................................226 Export to csv file .....................................................................................................................................228

    Import/Export xls/xlsx (Microsoft Office Excel) files ................................................... 230 Import xls/xlsx local files ........................................................................................................................230 Export to xls/xlsx files .............................................................................................................................234

    Import data with the wizard ........................................................................................... 236

    Charts....................................................................................................................... 243 Demo .............................................................................................................................. 243 Data sets ......................................................................................................................... 247 Chart wizard ................................................................................................................... 249

    Control chart window ..................................................................................................... 280 Pick-up points on chart ................................................................................................... 291

    C to R2 plots ................................................................................................................... 293

    Analytical based plot ...............................................................................................................................293 Vector based plot with lines and stems ....................................................................................................294 Animated vector based plot .....................................................................................................................297 Vector based plot with various lines, colors and points ...........................................................................299 Vector based multiple plot with legends and titles ..................................................................................301 Horizontal/Vertical lines method .............................................................................................................303 Vector based plot with error bars .............................................................................................................304 Vector based semi-log X plot with custom tick space .............................................................................305 Vector based semi-log Y plot ..................................................................................................................306 Vector based log-log plot with data cursor tip .........................................................................................307 Subplots ...................................................................................................................................................309 Greeks letters in legends and titles (LaTeX style) ...................................................................................312 Plots with dates in axis ............................................................................................................................313 Multiple axis on line plots .......................................................................................................................315 Magnifier on line plot ..............................................................................................................................318 2D vertical/horizontal bar charts..............................................................................................................319

    Multiple series bar chart ................................................................................................................... 319 Stacked bar chart ............................................................................................................................... 320 Stacked normalized bar chart ............................................................................................................ 321 Bar chart with error bars .................................................................................................................. 322 Bar chart with bar having a special a color ...................................................................................... 324 Tornado Chart ................................................................................................................................... 325 Bar chart with line and multiple axis ................................................................................................. 326

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 5

    Two series bar chart with multiple axis ............................................................................................. 327 Probability histogram with density curve (pdf) ................................................................................. 329

    Correlation 2D Heatmap ................................................................................................ 330 3D vertical bar charts ..................................................................................................... 332 2D/3D sector charts (cheese) .......................................................................................... 334 2D Surface/Area charts .................................................................................................. 337

    Radial (rose) bar chart/arrow (compass) chart ............................................................... 339 Pareto chart ..................................................................................................................... 342 Plotmatrix ....................................................................................................................... 343 3D parametric plots ........................................................................................................ 344

    Vector based 3D parametric line plot ......................................................................................................344 Animated or non-animated analytic based 3D parametric line plot .........................................................345 Animated vector based 3D parametric line plot .......................................................................................346 Vector based 3D stem parametric line plot ..............................................................................................347 Vector based 3D surface parametric plot .................................................................................................348

    3D surface plots .............................................................................................................. 359 ezsurf .......................................................................................................................................................359 ezsurfc .....................................................................................................................................................360 surf ..........................................................................................................................................................361

    surf with an explicit or implicit function! .......................................................................................... 369 Animated surf ..........................................................................................................................................370 mesh ........................................................................................................................................................371 surfc.........................................................................................................................................................374 contour3 (3d contours) ............................................................................................................................375 surf with surf projection ..........................................................................................................................378 contour (2d contours) ..............................................................................................................................381 waterfall ..................................................................................................................................................385 2D Gradient (quiver) ...............................................................................................................................386 3D Gradient .............................................................................................................................................387 Perpendicular vectors ..............................................................................................................................390 Surface plots of nonuniformly sampled data ...........................................................................................391

    Cubic (triangle base interpolation) ................................................................................................... 391 Delaunay (triangular connections) .................................................................................................... 393 Spline (biharmonic-spline) ................................................................................................................ 393

    Image mapping plots ...................................................................................................... 394 Map an image on a 2D plane chart ..........................................................................................................394 Map an image on a 3D surface chart .......................................................................................................395 Sphere plot with data mapping and animated rotation .............................................................................397

    Export animated plots as *.avi or *.gif........................................................................... 400 Export to *.avi .........................................................................................................................................400 Export to *.gif .........................................................................................................................................401

    Engineering/Simulations ................................................................................................ 402 Vector filed equation analysis .................................................................................................................402 Vector field snapshots analysis ................................................................................................................404

    Regression/Interpolation/Extropolation ......................................................................... 423 OLS univariate regression .......................................................................................................................423 Spline univariate interpolation .................................................................................................................425 Spline multivariate interpolation .............................................................................................................426

    Fractals ........................................................................................................................... 428 Save chart as image ........................................................................................................ 430

    Save on drive ...........................................................................................................................................430 Copy in the clipboard ..............................................................................................................................432

    Analysis ................................................................................................................... 433

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 6

    Estimate value of an univariate polynom on various points .......................................... 433

    Calculate the roots of an univariate polynom ................................................................. 433 Find the local min/max of an univariate function in a range ......................................... 436 Find the local min/max of a bivariate function .............................................................. 438

    1st Method (very old one) ........................................................................................................................438

    2nd

    Method (modern one).........................................................................................................................440 Discrete convolution ...................................................................................................... 440 Integration ...................................................................................................................... 443

    Pseudo-symbolic integration of polynoms ...............................................................................................443 Numeric integration .................................................................................................................................443 Numeric trapezoidal integration ..............................................................................................................444 Double numeric integration .....................................................................................................................445

    Derivation ....................................................................................................................... 446 Pseudo-symbolic derivation of polynoms ................................................................................................446 Numeric derivation ..................................................................................................................................447

    Differential equations (ODE/PDE) ................................................................................ 450 Pendulum (ODE) .....................................................................................................................................450 Lotka-Volterra (system of ODE) .............................................................................................................453 Lorenz attractor (system of ODE) ...........................................................................................................455 2 body motion (system of ODE) ..............................................................................................................457 Heat equation (parapolic PDE) ................................................................................................................461

    Fast Fourier Transform (DFT) ....................................................................................... 465

    Image processing ..................................................................................................... 468 Get image properties ...................................................................................................... 468 Show an image properly ................................................................................................. 470 Decompose images alpha layers .................................................................................... 471

    Build an image ............................................................................................................... 472 Plot some basic images manipulations and save image ................................................. 473

    Filter on luminosity value of a given channel ................................................................ 474

    Draw on an image and export the result ......................................................................... 475

    Compare images ............................................................................................................. 478 Add (superpose) images ................................................................................................. 480

    Video processing ..................................................................................................... 483 Get video properties ....................................................................................................... 483 Play video ....................................................................................................................... 484 Extract a frame ............................................................................................................... 485 Export all video frames in a folder ................................................................................. 486

    Build a video from a list of (pre-processed or not) images ............................................ 487

    Sound processing ..................................................................................................... 488 Get sound properties ....................................................................................................... 488 Play, Pause (resume), Resume, Stop sound playing ...................................................... 489 Plot a sound spectrum .................................................................................................... 490 Sound FFT (DFT)........................................................................................................... 492

    Generate a sound and save it .......................................................................................... 494 Play sounds in sequence or parallel ................................................................................ 495

    Scripting .................................................................................................................. 496 Script Editor most asked preferences ............................................................................. 496 Well commented script ................................................................................................... 498 Define help text .............................................................................................................. 500 Autocompletion .............................................................................................................. 501

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 7

    Conditional structure (if/switch) .................................................................................... 503 if statement ..............................................................................................................................................503 switch statement (with if...) .....................................................................................................................506

    Iteration structures .......................................................................................................... 507 For...End iteration structure (and optimization) .......................................................................................507 While...End iteration structure .................................................................................................................510

    Functions (functions files) .............................................................................................. 511 One input, One output (OIOO) ................................................................................................................511 Multiple inputs, One output (MIOO) .......................................................................................................512 One input, Multiple outputs (OIMO) .......................................................................................................513 Multiple inputs, Multiple outputs (MIMO) ..............................................................................................515 Optional arguments .................................................................................................................................516 Variables scope .......................................................................................................................................517

    Global vs Local variables .................................................................................................................. 517 Persistent variables ........................................................................................................................... 520

    Anonymous function as input, chart output .............................................................................................521 Recursive functions .................................................................................................................................523 Local functions (multiple functions in one script) ...................................................................................525 Profile a script .........................................................................................................................................526 Catching errors ........................................................................................................................................528 Multiple callable functions in one *.m file ..............................................................................................528

    Debugging technics ........................................................................................................ 531 M-lint ......................................................................................................................................................532

    M-lint real time analyzer ................................................................................................................... 532 M-lint reports ..................................................................................................................................... 533

    Echo on/Echo off .....................................................................................................................................537 For simple scripts .............................................................................................................................. 537 For functions scripts .......................................................................................................................... 541

    Manipulations during a run ......................................................................................................................542 Debugging (db...) functions .....................................................................................................................544

    Create a more complex wait bar ..................................................................................... 551

    Import an XML file ........................................................................................................ 552 Export an XML file ........................................................................................................ 555 MATLAB Automation ................................................................................................... 557

    Generate a Microsoft Word report ...........................................................................................................557 Put values into Microsoft Excel ...............................................................................................................559 Get values from a MS Excel VBA function ............................................................................................562

    Create a ToolBox (App) ................................................................................................. 564 Install/Uninstall a Toolbox ......................................................................................................................570

    Publish a script (documented script) .............................................................................. 574 Optimization tricks ......................................................................................................... 579

    Statistically check code efficiency ...........................................................................................................580 linspace vs sequence ................................................................................................................................582 Simple arithmetic operation vs bsxfun ....................................................................................................583 Create userforms .....................................................................................................................................585

    Symbolic calculations (Symbolic Toolbox) ................................................... 591 New main core features (to be complete) ............................................................... 591

    MATLAB 2014a (8.3) .................................................................................................... 591 MATLAB 2013b (8.2) ................................................................................................... 591

    MATLAB 2013a (8.1) .................................................................................................... 591 MATLAB 2012b (8.0) ................................................................................................... 591

    Limits....................................................................................................................... 592

    Derivate/Partial Derivate ......................................................................................... 593

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 8

    Integration ............................................................................................................... 594

    Taylor series ............................................................................................................ 594

    Heaviside function ................................................................................................... 596

    Matrix determinant .................................................................................................. 598

    Jacobien ................................................................................................................... 598

    MuPAD ................................................................................................................... 599

    Databases (with Database/Datafeed toolbox) ............................................... 601 Connect to mySQL 5.5.36 .............................................................................................. 601 Connect to Microsoft Access 2003/2010 (*.mdb/*.accdb) ............................................ 606 Connect to Oracle Express 11g ...................................................................................... 610

    Connect to MS SQL Server Express 2008 ..................................................................... 614 Connect to Yahoo! Finance ............................................................................................ 620

    Statistics (with Statistical and Curve Fitting Toolbox) ................................ 621 Datasets ................................................................................................................... 621

    Import/Export *.csv files as data set (data frame) .......................................................... 621 Import *.xls/*.xlsx files as data set (data frame) ............................................................ 623

    Convert structure array to data sets ................................................................................ 624 Clean messy or missing data in datasets ........................................................................ 626 Select/Remove column (variable) .................................................................................. 628 Create subsets and filter ................................................................................................. 628

    Delete rows and clean duplicates ................................................................................... 630 Add variables .................................................................................................................. 630

    Change variable name .................................................................................................... 631 Change column order ..................................................................................................... 631 Random sample of a dataset ........................................................................................... 632

    Sort a dataset .................................................................................................................. 633 Merge datasets ................................................................................................................ 634

    Plots ......................................................................................................................... 635 Histogram/CDF/PDF ...................................................................................................... 635 Box-Whisker plot ........................................................................................................... 638

    Scatter Group plot .......................................................................................................... 639 QQ plot ........................................................................................................................... 640 Histogram Scatter ........................................................................................................... 641 Copulas ........................................................................................................................... 642

    Gaussian copula .......................................................................................................................................642

    Descriptive statistics ................................................................................................ 645 Geometric mean ............................................................................................................. 645 Harmonic mean .............................................................................................................. 646 Trimmed mean (M-statistics) ......................................................................................... 646

    CDF/iCDF/Quantile/Centile........................................................................................... 648 Skewness/Kurtosis ......................................................................................................... 649

    Hypothesis tests ....................................................................................................... 652 Tests power, sample size and resolution ........................................................................ 652

    Power of a Z test ......................................................................................................................................652 Sample size of a one sample Z test ..........................................................................................................653 Difference (resolution) of a one sample Z test .........................................................................................653 Power of a t test .......................................................................................................................................654 Sample size of a one sample t test ...........................................................................................................654 Sample size of a one sample p test ..........................................................................................................655

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 9

    One sample Z-test ........................................................................................................... 655

    One sample t-test ............................................................................................................ 656 One sample t-test with explicit target mean ................................................................... 657 Two sample homoscedastic t-test ................................................................................... 658 Two sample heteroscedastic t-test (Welch test) ............................................................. 659 Paired t-test ..................................................................................................................... 660

    Chi-square variance test ................................................................................................. 661 Two sample F-test for equality of variances .................................................................. 662 Two sample Levene test for equality of variances ......................................................... 663

    Brown-Forsythe (median)........................................................................................................................663 Absolute Levene ......................................................................................................................................665 Quadratic Levene (square) .......................................................................................................................666

    Test for the median (one sample sign test) ..................................................................... 667 Binomial signed rank test (dixit: median test paired samples) ....................................... 668 Two unpaired samples Wilcoxon (Mann-Withney) rank sum test ................................ 669

    Wilcoxon signed rank test for 1 sample ......................................................................... 670 Wilcoxon signed rank test for two paired samples ........................................................ 671 ANOVA ......................................................................................................................... 672

    One-way fixed factor canonical ANOVA ................................................................................................672 Two-way fixed factors canonical ANOVA..............................................................................................675 Friedman's test (canonical non-parametric ANOVA based on ranks) ......................................................677 Kruskal-Wallis test (canonical non-parametric one-way ANOVA ..........................................................679

    Adequation tests ............................................................................................................. 682 Chi-square goodness of fit for Poisson distribution .................................................................................682 Kolmogorov-Smirnov (one sample) adequation test ................................................................................682 Anderson-Darling adequation test ...........................................................................................................684

    Regression Techniques ............................................................................................ 685 Ordinary Least Squares (parametric) univariate regression ........................................... 685

    1st method (coefficient and constant can not be extracted) ......................................................................685

    2nd

    method (coefficient and constant and others can be extracted) ..........................................................689 3

    rd method (using Curve Fitting Toolbox) ...............................................................................................691

    Manage outliers .......................................................................................................................................697 Residuals and Leverage (residual diagnosis) ...........................................................................................701 Regression diagnostics wizard .................................................................................................................702

    Ordinary Least Squares (parametric) multivariate regression (with/without interactions)

    ........................................................................................................................................ 704 1

    st method (coefficient and constant can not be extracted) ......................................................................704

    2nd

    method (coefficient and constant and others can be extracted) ..........................................................707 Polynomial multivariate regression using OLS and Curve fit Toolbox ......................... 709 (Forward) Stepwise regression ....................................................................................... 712 General Linear Models (GLM) ...................................................................................... 715

    Normal regression ...................................................................................................................................715 Log-linear Poisson regression..................................................................................................................716 Binomial (logistic) regression..................................................................................................................717

    Data Mining/Machine Learning .............................................................................. 719 K-means (euclidian full) ................................................................................................. 719

    Hierarchical ascendant (CAH) Dendrogram .................................................................. 726 CART Classification trees (Gini index based) ............................................................... 731 k-NN (k-Nearest Neighbors) .......................................................................................... 735 Naive Bayes .................................................................................................................... 737 Parametric Principal Component Analysis .................................................................... 740

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 10

    Linear Discriminant Analysis (Fisher Discriminant) ..................................................... 745

    Control charts (CC) ................................................................................................. 752 P attribute CC ................................................................................................................. 754 NP attribute CC .............................................................................................................. 756 C attribute CC ................................................................................................................. 758 U attribute CC ................................................................................................................ 760 Xbar-R continuous CC ................................................................................................... 762

    Rbar-R continuous CC ................................................................................................... 763 Sbar-S continuous CC ................................................................................................... 765 I-EM continuous CC ...................................................................................................... 766 Moving Average continuous CC .................................................................................... 769

    Design of experiments ............................................................................................. 771 Two-level full factorial design ....................................................................................... 771

    Full factorial design ........................................................................................................ 771 Fractional factorial design .............................................................................................. 772

    Simulations techniques ............................................................................................ 773 Kernel Smoothing .......................................................................................................... 773

    Monte Carlo traditional technique .................................................................................. 775 Monte Carlo antithetic variables technique .................................................................... 777 Monte Carlo with antithetic quasi-random variables technique ..................................... 779 Latin HyperCube ............................................................................................................ 780

    Monte Carlo by control variable (variance reduction technique) .................................. 782 Monte Carlo importance sampling ................................................................................. 784

    Optimization (with Op timization Toolbox/Global Optimization Toolbox)

    ........................................................................................................................... 788 Linear optimization using LP Simplex (LPS) ......................................................... 788

    LP-S Factory optimization problem (inequality linear system) ..................................... 788

    LP-S Naive (without covariance...) Markowitz parametric portfolio optimization

    problem (equality linear system without target value) ................................................... 791 LP-S Naive (without covariance...) Markowitz parametric portfolio optimization

    problem (equality linear system with target value) ........................................................ 792

    Function constrained optimization (FCO) .............................................................. 793 FCO with constraints and without specific target .......................................................... 793 FCO with constraints and specific target ....................................................................... 795 FCO with non linear constraints (and specific target) .................................................... 796

    Quadratic optimization (QO) .................................................................................. 798 QO using conjugate gradient method (Q-CG) ............................................................... 798

    QO using interior point convex method (Q-IPC) ........................................................... 800

    Finance (with Finance/Optimization and Econometrics Toolboxes) ......... 801 Fractional prices ...................................................................................................... 801

    Return ...................................................................................................................... 801

    Maximum Draw Down ............................................................................................ 802

    Box-Cox transformation .......................................................................................... 802

    Simple capital calculations ...................................................................................... 804 Composed Interest (fixed future value) .......................................................................... 804 Composed Interest (fixed present value) ........................................................................ 805

    Amortization and deprecation ................................................................................. 806 Straight line deprecation (SLN) ..................................................................................... 806

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 11

    Sum of years digit (SYD) ............................................................................................... 806

    Fixed declining-balance depreciation schedule (DB) .................................................... 807 Double declining balance (DDB) ................................................................................... 807

    Loans and credits ..................................................................................................... 808 Payment for a loan based on constant payments and a constant interest rate (PMT) .... 808 Principal Payment (PPMT) ............................................................................................ 809 Interest Payment (IPMT) ................................................................................................ 810

    Payment Present Value (PV) .......................................................................................... 811 Plot resume of loan payment .......................................................................................... 812

    Annuities ................................................................................................................. 814 Postnumerando actual annuity value (PV) ..................................................................... 814 Postnumerando forward annuity value (PV) .................................................................. 814 Postnumerando number of periods (NPER) ................................................................... 815

    Postnumerando annuity rate (ANNURATE) ................................................................. 815

    Corporate finance .................................................................................................... 816 Net Present Value (NPV) ............................................................................................... 816

    Periodic NPV ..........................................................................................................................................816 non-Periodic NPV ...................................................................................................................................816

    Internal Rate of Return (IRR) ......................................................................................... 817 Periodic IRR ............................................................................................................................................817 non-Periodic IRR .....................................................................................................................................817

    Modified Internal Rate of Return (MIRR) ..................................................................... 818

    Treasure bonds/securities calculations .................................................................... 819 Clean price of a security (PRICE) .................................................................................. 819 Price of treasury bond/security (TBILLPRICE) ............................................................ 819

    Yield of a treasury bond (TBILLYIELD) ...................................................................... 820 Discount rate of a security (DISC) ................................................................................. 821

    Annual yield for a discounted security (YIELDDISC) .................................................. 821

    Bond duration and Macaulay duration ........................................................................... 822

    Naive Markowitz portfolio models ......................................................................... 823 Optimal short-long portfolio (without transaction costs) ............................................... 824

    Optimal portfolio with implicit constraints no short sales allowed (without transaction

    costs) ............................................................................................................................... 826 Optimal portfolio with implicit constraints no short sales allowed (with transaction costs)

    ........................................................................................................................................ 831 Get portfolios on the efficient frontier with explicit constraints (without transaction

    costs) ............................................................................................................................... 832 Equally weighted portfolio (EWP) (without transaction costs) ..................................... 834 Maximum Sharpe Ratio (max. diversification) portfolio with implicit constraints

    (without costs) ................................................................................................................ 836 Optimal portfolios for target returns and CVaR minimization (without transaction costs)

    ........................................................................................................................................ 838

    Optimal portfolios for target risks and CVaR minimization (without transaction costs)

    ........................................................................................................................................ 839

    Values at risk (VaR) ................................................................................................ 840 Parametric relative VaR ................................................................................................. 840

    Parametric absolute VaR ................................................................................................ 840 non-Parametric (absolute) VaR ...................................................................................... 840 Condition (absolute) Normal VaR ................................................................................. 840

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 12

    Options Pricing & Monitoring ................................................................................ 843 Pricing European Call & Put .......................................................................................... 843

    European Call & Put implied volatiliy ........................................................................... 845 European Call & Put delta .............................................................................................. 845 European Option (call/put) Gamma ............................................................................... 846 European Option (call/put) Vega ................................................................................... 846 Option european lambda ................................................................................................ 846

    Option european theta .................................................................................................... 847 Option european rho ....................................................................................................... 847 Implied volatility surface of an European option ........................................................... 847 Volatility smile of an European option .......................................................................... 848 CRR binomial European option pricing model .............................................................. 853

    Time series .............................................................................................................. 855 Autocorrelation ............................................................................................................... 855 Partial autocorrelation .................................................................................................... 858

    Moving average MM3 (without ARIMA) ..................................................................... 860 Simple Exponential Weighted Moving Average (EWMA) ........................................... 862 Univariate AR(2)/ARIMA(2,0,0) ................................................................................... 865 Univariate ARIMA(0,0,0)/Moving Average .................................................................. 868 Univariate ARIMA(0,1,0) .............................................................................................. 871

    Univariate ARIMA(0,1,1)/Simple Exponential Smoothing (EWMA) .......................... 875 Univariate ARIMA(0,2,2)/Holt's double exponential smoothing .................................. 877

    Univariate ARMA(1,1)/ARIMA(1,0,1) ......................................................................... 880 Univariate GARCH(1,1) ................................................................................................ 883

    Applications (without Financial Toolbox) .............................................................. 888 Bond portfolio with duration/convexity targets ............................................................. 888

    Brownian motion and Wiener Process ........................................................................... 889 Risk-return asset pricing models .................................................................................... 891

    Capital Asset Pricing Model (CAPM) .....................................................................................................891 Three-factor Fama-French model (FFM) .................................................................................................892 Fama-McBeth ..........................................................................................................................................894

    Options Pricing ............................................................................................................... 897 CRR binomial option pricing model without Financial Toolbox .............................................................897 Drifted CRR binomial option pricing model without Financial Toolbox .................................................898 Jarrow-Rudd binomial option pricing model without Financial Toolbox ................................................900 Jarrow-Rudd binomial risk neutral option pricing model without Financial Toolbox ..............................901 Leisen-Reimer binomial option pricing model without Financial Toolbox .............................................903 Tian binomial option pricing model without Financial Toolbox ..............................................................905

    Portfolios models ............................................................................................................ 907 Global Minimum Variance Efficient Portfolios (GMVP) without Toolboxes using langrangien multiplier

    ................................................................................................................................................................907 Global Minimum Variance Efficient Portfolios (GMVP) using only Optimization Toolbox ..................908 Portfolio Performance .............................................................................................................................917 Michaud Optimal Portfolio (bootstrap/resample efficiency) ....................................................................919 CVaR portfolio ........................................................................................................................................923 Black-Litermann portfolio .......................................................................................................................930

    Signal processing (Signal processing Toolbox) ............................................. 934

    Circuit Analysis (Simulink Toolbox) ............................................................. 938 Create an RLC circuit .............................................................................................. 946

    Neural Networks (Neural Network Toolbox) ............................................... 953

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 13

    Image Processing (with Image Processing and Acquisition Toolboxes) .... 965 Play with the image tool wizard .............................................................................. 965

    Image as a function ................................................................................................. 969

    Image histogram ...................................................................................................... 971

    Filters (blur, motion) on an image ........................................................................... 975

    Crop an image ......................................................................................................... 979

    Convert a *.gif file into an *.avi.............................................................................. 980

    Overlay images with masks..................................................................................... 982

    Objects recognition and extraction .......................................................................... 986 Without references ......................................................................................................... 986 With reference ................................................................................................................ 987

    Image filters (convolution) ...................................................................................... 993 Gaussian (blur) filter ...................................................................................................... 993

    1st method using imfilter() .......................................................................................................................993

    2nd

    method using convn().........................................................................................................................995 3

    rd method using conv2() .........................................................................................................................996

    External Camera Acquisition .................................................................................. 997

    Parallel Computing (with Parallel Computing Toolbox) .......................... 1003 Clusters computing ................................................................................................ 1003

    NVidia GPU computing ........................................................................................ 1007

    Advanced scripting (C#, C++, Compiler Toolbox) .................................... 1008 Create a *.p (protected script) file (aka "pcode") .................................................. 1008

    C MEX file ............................................................................................................ 1009

    Create executable (*.exe) ...................................................................................... 1012

    Call MATLAB from C# (VS Express 2010) ........................................................ 1016

    Call MATLAB from C++ (VS Express 2010 x64) ............................................... 1022

    Compile DLL and call from C# ............................................................................ 1048 Passing a scalar ............................................................................................................. 1048 Passing a constant, vector and matrix .......................................................................... 1058

    Table 1 Standardized color codes ........................................................................................... 288 Table 2 Common dates format syntaxes ................................................................................ 314 Tableau 3 ODE solvers .......................................................................................................... 451

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 14

    MATLAB is the abbreviation for MAtrix LABoratory and is actually the leading

    environment for technical computing. Originally written in Fortran, by C Moler, MATLAB

    was designed to facilitate the access to the matrix framework developed for the LINPACK

    and EISPACK projects. The current version, written in C by the MathWorks Inc., exist in a

    Professional version and a Student version. Its availability is ensured on multiple platforms:

    Linux, Mac, Windows and several parallel machines.

    MATLAB is a comprehensive and almost easy to use for scientific computing but very

    expensive for students or independent/small companies (unlike R, Octave, Scilab or other free

    open source equivalent alternatives). It provides to engineers, researchers and any scientific

    an interactive system that integrates a lot of scientific numerical computation and

    visualization algorithms (but can do much better!). It is a powerful, almost open and

    programmable system allowing especially remarkable gains in productivity and creativity.

    MATLAB is relatively complete, open and extensible for calculation and visualization

    algorithms. It has hundreds (if not thousands, depending on the version and the optional

    toolbox around the MATLAB core solution) mathematical, scientific and technical functions.

    The matrix approach allows MATLAB to process data without large size variables and

    perform numeric and symbolic calculations quickly and reliably. Thanks to the graphics

    capabilities of MATLAB , it becomes very easy to interactively change the various graphics

    settings and to adapt them according to our wishes.

    The fact that the source code of some functions integrated in MATLAB can be inspected

    gives sometimes the engineers to develop better custom made solutions (also do Python

    Scipy...).

    MATLAB has its own language that is very fast and allows time savings for Engineers

    compared to other languages like C, Fortran, Python and the TurboPascal even if the language

    is horrible to use (non-typed, bad closed lined, etc.). With MATLAB , we can make

    connections dynamically, to C, .Net or Fortran programs, exchange data with other

    applications (via DDE: MATLAB server or client) or use MATLAB as analysis and

    visualization engine.

    In terms of development speed, MATLAB is always faster than C/C++. This is to be expected

    with a higher-level language, just as C/C++ is faster to develop with than assembler.

    But a C/C++ programmer with an infinite amount of development time can beat MATLABs

    speed, in the same way an assembly programmer with an infinite time can beat a C/C++

    programmer.

    MATLAB also includes a set of tools specific to engineering areas called Toolboxes.

    Essential for most users, Toolboxes are collections of functions that extend the MATLAB

    environment to solve specific types of problems. The areas covered are varied and include

    signal processing, automatic control, system identification, neural networks, fuzzy logic,

    structure calculation, statistics, database access, etc.

    This document can also strongly help you to prepare the following certifications:

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 15

    Like all my e-books you will found here only subjects that are proven and calculated by

    hand in the theoretical course.

    MATLAB Evolution

    MATLAB was Programmed by Cleve Moler as an interface for EISPACK & LINPACK.

    1957: Moler goes to Caltech. Studies numerical Analysis

    1961: Goes to Stanford. Works with G. Forsythe on Laplacian eigenvalues.

    1977: 1st edition of MATLAB ; 2000 lines of Fortran 80 functions (now more than 8'000 functions)

    1979: Met with Jack Little in Stanford. Started working on porting it to C

    1984: Mathworks is founded

    Below is a screen shot from MATLAB 3.13:

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 16

    Here's a screen shot of MATLAB 4.2c (1994):

    Here's a screen shot from MATLAB 5.1 in 1997:

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 17

    The last big change was in MATLAB 6.5 in 2002:

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 18

    MATLAB 7:

    MATLAB 8:

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 19

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 20

    ISOZ Vincent

    Resident until this date in Lausanne (Switzerland)

    Trainer: Physicist Engineer HES (B.Sc.)

    Year of birth: 1978

    Director of the company Scientific Evolution Srl specialized in consulting and training for

    high-potentials especially quantitative analysts in project management, quality, engineering,

    finance and decision making. Incidentally, happy freelancer that gathers since young

    information from articles everywhere and now addicted to everything related to applied

    mathematics in the management of organization (Businesses, States), TQM (Total Quality

    Management) with Post-taylorisme and related softwares.

    Consultant in applied mathematics tutoring quantitative analysts (graduate and posgraduate)

    in French, English and German and author of several French and English eBooks in the

    following areas:

    - statistical process control (parametric and nonparametric methods)

    - predictive modeling / advanced decision (decision trees, Markov chains)

    - Operations Research (quasi-Newton, simplex, genetic algorithms, algorithm GRG)

    - data mining (neural networks, PCA, CA, regressions, scoring, clustering, etc.)

    - risk modeling in project management and corporate finance (monte-carlo, bootstrapping)

    - project management (best practices and theoretical models EFQM+Six Sigma, MS Office Project)

    - ISO 9001:2008, 5807:1985, 10015:1999, 31000+31010:2009, 8258:1991, 10017:2003

    - Adobe Photoshop and Illustrator

    - 12 applications of the Microsoft Office System (Project, Visio, SharePoint, Access, etc.)

    At this date I made interventions in over 200 companies, including some of to the Fortune 500

    according to the 2009 listing and also in three universities and engineering schools in

    Switzerland for databases and stochastic risk simulations trainings. I also gave training in

    several multinational to executives in one to one. Sometimes I give training on softwares like

    MS Project, MS Visio, MS Access and approximately 20 others softwares that I delegated the

    training organization to companies specialized in computer softwares trainings (university

    degree level and below).

    Finally, I would advise anyone wishing to really master the subject to read my e-book on

    Applied Mathematics (~ 4'900 pages).

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 21

    KOLANI Daname

    I'm currently living in Casablanca (Maroc)

    Graduate in Finance from the Business School ENCG-

    Casablanca

    Born in 1990, I am from Togo.

    I am passionate in the field of finance, economics, and other corollary as econometrics, also in

    statistics & probabilities. Apart, the theories associated with those fields, I have a great

    interest in tools that underpin all of these areas. I am bilingual (French & English) and my

    specific competences include:

    - Corporate Finance (Investment decision & Financing, Financial Analysis and Diagnosis, Management Control and Company Evaluation...)

    - Market finance (financial portfolio management, financial asset valuation, risk management tools ...)

    I also have an interest in computational finance skills in R Project, VBA, Excel, MATLAB ,

    EViews & SPSS.

    I aspire to get into consulting and thereby contribute to the optimization of financial decisions

    and the implementation of efficient financial strategy consistent with the business model of

    companies.

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 22

    The content of this document is elaborated by a development process by which volunteers

    reach a consensus. This process that brings together volunteers, research also the point of

    view of people interested in the topic of this document. The person in charge of this document

    administers the process and establishes rules to promote fairness in the consensus approach. It

    is also responsible for drafting the text, sometime for testing/evaluating or independently

    verifying the accuracy or completeness of the presented information.

    We decline no responsibility for any injury, damage or any other kind, special, incidental,

    consequential or compensatory, arising from the publication, application or reliance on the

    content of this document. We make no express or implied warranty on the accuracy or

    completeness of any information published in this document, and do not guarantee that the

    information contained in this document meet any specific need or goal of the reader. We do

    not guarantee the performance of products or services of one manufacturer or vendor solely

    by virtue of the document content.

    By publishing texts, it is not the intention of this document to provide services on behalf of

    any person or entity or performing any task to be accomplished by any person or entity for the

    benefit of a third party. Anyone using this document should rely on its own independent

    judgment or, where that is appropriate, seek the advice of a qualified expert to determine how

    to exercise reasonable care under all circumstances. The information and standards on the

    topic covered by this document may be available from other sources that the reader may wish

    to visit in search of points of view or additional information not covered by the contents of

    this document.

    We have no power in order to enforce compliance with the contents of this document, and we

    do not undertake to monitor or enforce such compliance. We have no certification, testing or

    inspection activity of products, designs or installations for safety or health of persons and

    property. Any certification or other statement of compliance regarding information relating to

    health or safety of persons and property, mentioned in this document, can not possibly be

    attributed to the content of this document and remains under the responsibility of the

    certification center or the concerned reporter.

  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 23

    As a reader of this document, you are the critic and the most important commentator. Your

    opinion counts and it is very interesting for us to know what is good, what can be better and

    topics that you would like to see be treated.

    You can send me an e-mail to share what you liked or disliked in this document to ensure

    continuous improvement.

    If you want to complete this support with a subject that is important to you and for which you

    have the mathematical proof please do not hesitate to contact me. I will integrate the subject

    specifying your name and surname.

    Note that unfortunately I can not answer to technical engineering questions or business issues

    for free by email for obvious professional reasons.

    E-mail: [email protected]

    With that, I want to say a huge "THANK YOU" to all of my customers, partners,

    colleagues, students and friends who with their feedback, return on experience helped

    me write this e-book.

    mailto:[email protected]
  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 24

    General

    http://ww.sciences.ch (the companion website containing mathematical proofs)

    http://ww.google.com

    http://www.youtube.com

    http://www.scribd.com

    http://www.mathworks.com/products/

    http://www.mathworks.ch/ch/help/matlab/release-notes.html

    http://www.mathworks.com/matlabcentral/fileexchange/

    http://www.mathworks.ch/discovery/

    http://www.mathworks.ch/discovery/gallery.html

    http://www.mathworks.com/matlabcentral/newsreader/

    http://www.undocumentedmatlab.com

    http://www.imageprocessingblog.com

    http://www.alphorm.com (for people that want a part of this eBook as a video training):

    z

    www.sciences.chwww.google.comwww.youtube.comwww.scribd.comwww.mathworks.com/products/www.mathworks.ch/ch/help/matlab/release-notes.htmlwww.mathworks.com/matlabcentral/fileexchange/www.mathworks.ch/discovery/www.mathworks.ch/discovery/gallery.htmlwww.mathworks.com/matlabcentral/newsreader/www.undocumentedmatlab.comwww.imageprocessingblog.comhttp://www.alphorm.com/
  • Vincent ISOZ, Daname KOLANI Sciences.ch

    MATLAB 25

    Forums

    http://ww.mathworks.ch/matlabcentral/answers/

    http://www.talkstats.com

    http://matlab.developpez.com

    Non