MATLAB opas

Pohjautuu vapaasti levitettävään oppaan versioon:

MATLAB Primer

Kermit Sigmon

Second Edition


Some additions and comments in Finnish (and on Maple)

8.9.2000
Heikki Apiola http://www.math.hut.fi/~apiola
Matematiikan laitos
Teknillinen korkeakoulu
e-mail: heikki.apiola@hut.fi

Sisältö


1. Viitteitä

www-viitteitä

0. Introduction

MATLAB is an interactive, matrix-based system for scientific and engineering calculations. You can solve complex numerical problems without actually writing a program. The name MATLAB is an abbreviation for MATrix LABoratory.

Alunperin: Moler: University of New Mexico n. 1980, Fortran-ohjelma, jossa pienimuotoiseksi tarkoitettuun matriisitulkkiin oli liitetty "state-of-the art" lineaarialgebran Fortran-kirjastorutiinieja Linpack- ja Eispack-kirjastoista. (Pohjana Blas, Basic Linear Algebra Subprograms, nykyisin Linpack+Eispack ==> Lapack)

Esikuvia kielelle: "Speak Easy" (mikä lienee) ja APL (Kenneth Iverson 1960-luvulla, Jim Brown, IBM Yorktown Heights: APL2 1984, ...)

Nykyisin : "Teollisuusstandardin asemassa", suuri määrä ammattimaisia toolboxeja.

Muuten, miksei ole Matlabin statistics-toolboxia (vai onko?) Kieli on vahva suurten aineistojen käsittelyyn. APL:llä on tehty paljon tilasto-ohjelmia, kaupallisista esim. Statgraphics, ja APL-kieltä on käytetty tilastotieteen opetuksessa monessa paikassa, meilläkin: Tampereella, Jyväskylässä, Joensuussa...


                              < M A T L A B >
                  Copyright 1984-1999 The MathWorks, Inc.
                         Version 5.3.0.10183 (R11)
                                Jan 21 1999

 
  To get started, type one of these: helpwin, helpdesk, or demo.
  For product information, type tour or visit www.mathworks.com.

>> path

        /usr/local/matlab5.3/toolbox/simulink/simulink
        /usr/local/matlab5.3/toolbox/simulink/blocks
        /usr/local/matlab5.3/toolbox/simulink/simdemos
        /usr/local/matlab5.3/toolbox/simulink/dee
        /usr/local/matlab5.3/toolbox/comm/comm
        /usr/local/matlab5.3/toolbox/comm/commsim
        /usr/local/matlab5.3/toolbox/comm/commsfun
        /usr/local/matlab5.3/toolbox/comm/commmasks
        /usr/local/matlab5.3/toolbox/compiler
        /usr/local/matlab5.3/toolbox/control
        /usr/local/matlab5.3/toolbox/control/ctrlguis
        /usr/local/matlab5.3/toolbox/control/obsolete
        /usr/local/matlab5.3/toolbox/finance/finance
        /usr/local/matlab5.3/toolbox/finance/calendar
        /usr/local/matlab5.3/toolbox/finance/findemos
        /usr/local/matlab5.3/toolbox/fuzzy/fuzzy
        /usr/local/matlab5.3/toolbox/fuzzy/fuzdemos
        /usr/local/matlab5.3/toolbox/hosa/hosa
        /usr/local/matlab5.3/toolbox/hosa/hosademo
        /usr/local/matlab5.3/toolbox/ident
        /usr/local/matlab5.3/toolbox/images/images
        /usr/local/matlab5.3/toolbox/images/imdemos
        /usr/local/matlab5.3/toolbox/local
        /usr/local/matlab5.3/toolbox/ncd
        /usr/local/matlab5.3/toolbox/nnet/nnet
        /usr/local/matlab5.3/toolbox/nnet/nndemos
        /usr/local/matlab5.3/toolbox/nnet/nnutils
        /usr/local/matlab5.3/toolbox/nnet/nnobsolete
        /usr/local/matlab5.3/toolbox/optim
        /usr/local/matlab5.3/toolbox/pde
        /usr/local/matlab5.3/toolbox/sb2sl
        /usr/local/matlab5.3/toolbox/signal/signal
        /usr/local/matlab5.3/toolbox/signal/siggui
        /usr/local/matlab5.3/toolbox/signal/sigdemos
        /usr/local/matlab5.3/toolbox/splines
        /usr/local/matlab5.3/toolbox/stateflow/stateflow
        /usr/local/matlab5.3/toolbox/stateflow/sfdemos
        /usr/local/matlab5.3/toolbox/stats
        /usr/local/matlab5.3/toolbox/symbolic
        /usr/local/matlab5.3/toolbox/tour
        /usr/local/matlab5.3/toolbox/wavelet/wavelet
        /usr/local/matlab5.3/toolbox/wavelet/wavedemo

help, helpwin, helpdesk, lookfor

helpdesk käynnistää www-pohjaisen laajan avustus- ja opiskelujärjestelmän hakuineen ym. Suositeltavia valintoja aluksi:

You should liberally use the on-line help facility for more detailed information. After entering MATLAB as described in section 1, the command help (or helpwin ) will display a list of functions for which on-line help is available; the command help functionname will give information about a specific function. The command help eig, for example, will give information about the eigenvalue function eig. You can preview some of the features of MATLAB by entering the command demo.

lookfor etsintään

MATLAB is available for a number of environments. (Kaikkiin saa) There is a relatively inexpensive Student Edition available from Prentice Hall publishers. The information in these notes applies generally to all of these environments.

MATLAB is licensed by The MathWorks, Inc., Cochituate Place, 24 Prime Park Way, Natick, MA 01760, (508)653-1415, Fax: (508)653-2997, Email: info@mathworks.com. Copyright (C) 1989, 1992 by Kermit Sigmon 


1. Accessing MATLAB

On most systems, after logging in one can enter MATLAB with the system command matlab and exit MATLAB with the command exit or quit.
TKK:n UNIX:ssa
        use matlab
        matlab
and exit it with the command:
        >>  quit
On systems permitting multiple processes, such as a Unix system, you will find it convenient, for reasons discussed in section 14, to

keep both MATLAB and your local editor active. Nyt se on uskottava!


2. Entering matrices

MATLAB works with essentially only one kind of object-a rectangular numerical matrix with possibly complex entries; all variables represent matrices. In some situations, 1-by-1 matrices are interpreted as scalars and matrices with only one row or one column are interpreted as vectors.

Versiossa 5 on myös sisäkkäisiä ja moniulotteisia rakenteita.

Matrices can be introduced into MATLAB in several different ways:

For example, either of the statements
        A = [1 2 3; 4 5 6; 7 8 9]
and
        A = [
        1  2  3
        4  5  6
        7  8  9 ]
creates the obvious 3-by-3 matrix and assigns it to a variable A. Try it. The elements within a row of a matrix may be separated by commas as well as a blank.

When listing a number in exponential form (e.g. 2.34e-9), blank spaces must be avoided. Listing entries of a large matrix is best done in an M-file, where errors can be easily edited away (see sections 12 and 14).

rand,hilb,magic

The built-in functions rand, magic, and hilb, for example, provide an easy way to create matrices with which to experiment. The command rand(m,n) will create an m x n matrix with randomly generated entries distributed uniformly between 0 and 1

magic(m,n) will create an integral n x n matrix which is a magic square (rows and columns have common sum); hilb(m,n) will create the m x n Hilbert matrix, the king of ill-conditioned matrices ( m and n denote, of course, positive integers). Matrices can also be generated with a for-loop (see section 6 below).

Matriisin alkion poiminta

Individual matrix and vector entries can be referenced with indices inside parentheses in the usual manner. For example, A(2,3) denotes the entry in the second row, third column of matrix A and x(3) denotes the third coordinate of vector x. Try it. A matrix or a vector will only accept positive integers as indices.

A(1,:) ilmaisee A-matriisin ensimmäisen rivin (yksinäinen kaksoispiste jälkimmäisenä indeksinä tarkoittaa, että sarakeindeksi käy läpi kaikki arvonsa . Vastaavasti A(:,2) tarkoitta A:n toista saraketta.

Indeksointia käsitellään tarkemmin ... Kts. myös [SKK] 2.9, ss. 23 - 25.


3. Matrix operations, array operations

The following matrix operations are available in MATLAB:
        +    addition
        -    subtraction
        *    multiplication
        ^    power
        '    transpose
        \    left division
        /    right division
These matrix operations apply, of course, to scalars (1-by-1 matrices) as well. If the sizes of the matrices are incompatible for the matrix operation, an error message will result, except in the case of scalar-matrix operations (for addition, subtraction, and division as well as for multiplication) in which case each entry of the matrix is operated on by the scalar.

The "matrix division" operations deserve special comment. If A is an invertible square matrix and b is a compatible column, resp. row, vector, then

        x=A \ b
is the solution of A*x=b and, resp.,
        x=b/A
is the solution of x*A=b . In left division, if A is square, then it is factored using Gaussian elimination and these factors are used to solve A*x=b. If A is not square, it is factored using Householder orthogonalization with column pivoting and the factors are used to solve the under- or over- determined system in the least squares sense. Right division is defined in terms of left division by
        b/A=(A' \ b')'
Array operations. The matrix operations of addition and subtraction already operate entry-wise but the other matrix operations given above do not-they are matrix operations. It is important to observe that these other operations,
        *  ,   ^  ,  \  , and /,
can be made to operate entry-wise by preceding them by a period. For example, either
        [1,2,3,4].*[1,2,3,4]
or
        [1,2,3,4].^2
will yield [1,4,9,16]. Try it. This is particularly useful when using Matlab graphics.

Tee itsellesi selväksi pisteittäiset, vastinalkioittain toimivat operaatiot.


4. Statements, expressions, and variables; saving a session

MATLAB is an expression language; the expressions you type are interpreted and evaluated. MATLAB statements are usually of the form
        variable = expression,
or simply
        expression
Expressions are usually composed from operators, functions, and variable names. Evaluation of the expression produces a matrix, which is then displayed on the screen and assigned to the variable for future use. If the variable name and = sign are omitted, a variable ans (for answer) is automatically created to which the result is assigned.

A statement is normally terminated with the carriage return. However, a statement can be continued to the next line with three or more periods followed by a carriage return. On the other hand, several statements can be placed on a single line if separated by commas or semicolons.

If the last character of a statement is a semicolon, the printing is suppressed, but the assignment is carried out. This is essential in suppressing unwanted printing of intermediate results.

Vertailua Mapleen

Matlab  Maple 
>> muuttuja=lauseke 
Loppumerkki ei pakollinen (;) estää tulostuksen 
> muuttuja:=lauseke; 
Loppumerkki (; tai :) pakollinen, kaksoispiste estää tulostuksen. 
Matemaattisten lausekkeiden syntaksi on hyvin pitkälle sama, paitsi Matlabissa käytetään lausekkeissa hyvin usein piste-alkuisia kerto- ja jako-operaattoreita. Maplessa maksetaan "peruspisteettömyydestä" hankalampana matriisikertosyntaksina evalm( A&*B);

MATLAB is case-sensitive in the names of commands, functions, and variables. Samoin on Maple.


The command who will list the variables currently in the workspace. Komento whos antaa tarkempaa tietoa. A variable can be cleared from the workspace with the command clear variablename. The command clear alone will clear all nonpermanent variables.

The permanent variable eps (epsilon) gives the machine precision-about 10-16 on most machines. It is useful in determining tolerences for convergence of iterative processes.

A runaway display or computation can be stopped on most machines without leaving MATLAB with CTRL-C (CTRL-BREAK on a PC).

Saving a session. When one logs out or exits MATLAB all variables are lost. However, invoking the command save before exiting causes all variables to be written to a non-human-readable diskfile named matlab.mat. When one later reenters MATLAB, the command load will restore the workspace to its former state.

Huom! Yllä oleva save ei tarkoita, että Matlab- työ tallettuisi. Siis muuttujat kyllä, mutta komennot eivät. Siten save -komento on tavallisesti varsin hyödytön. Työn talletus tehdään pitämällä editori-ikkuna auki ("köyhän miehen worksheet", kuten L1.html:ssä puhuttiin, mutta ei ollenkaan huono.)


5. Matrix building functions

Convenient matrix building functions are
        eye(10,10)           identity matrix
        zeros(10,10)         matrix of zeros
        ones(10,10)          matrix of ones
        diag(A)           returns diagonal M.E. as vector
        triu(A)           upper triangular part of a matrix
        tril(A)           lower triangular part of a matrix
        rand(10,10)          randomly generated matrix
        hilb(5,5)           Hilbert matrix
        magic(5,5)          magic square
        toeplitz          see help toeplitz
For example, zeros(m,n) produces an m-by-n matrix of zeros. size(A) gives the size of A (big surprise !), ai niin, suomeksi, olkoon ... Thus if A is a matrix, then zeros(size(A)) produces a matrix of zeros of the same size as A .

If x is a vector, diag(x) is the diagonal matrix with x down the diagonal; if A is a square matrix, then diag(A) is a vector consisting of the diagonal of A . What is diag(diag(A))?

Matrices can be built from blocks. For example, if A is a 3-by-3 matrix, then

        B = [A, zeros(3,2); zeros(2,3), eye(2)]
will build a certain 5-by-5 matrix.

Kokeillaan solumatriisia:

       A = [1 2 3; 4 5 6; 7 8 9]
       B = {A, zeros(3,2); zeros(2,3), eye(2)}
       cellplot(B),shg
       celldisp(B)
       C={'Otsikko';B}
       C{1,1}
       C{2,1}
       C{2,1}{1,1}
       C{2,1}{1,1}(1,2)

    ans =

       2



5.5 Vektorien muodostaminen, (:) ja linspace

Olemme muodostaneet vektoreita luettelemalla alkiot hakasuluissa, sarakevektorissa erottimena käytetään puolipistettä (kysehän on m x 1 matriisista).

1:10 antaa vektorin [1,2,3,4,5,6,7,8,9,10] ja yleisemmin a:h:b vektorin [a,a+h,a+2h,...,b] . Tarkista help : , jos haluat tietää, mikä on viimeinen alkio, ellei mene tasan.)

Usein on tarpeen jakaa annettu väli tasan n:ään osaan. Se voitaisiin tehdä tyyliin

  h=(b-a)/n
  x=a:h:b
Tähän on myös valmis funktio linspace .

x=linspace(a,b,n);

Funktiolla linspace on myös muoto linspace(a,b), jolloin n:n oletusarvona käytetään lukua 100. Tämä on tavallisessa käyrien piirtämisessä usein sopiva arvo.

Jos haluamme muodostaa matriisin, jonka 1. sarake on väli [-1,1] jaettuna tasavälisesti 10 osaan ja toisena kunkin jakopisteen neliö, ja laitetaan nyt vielä kolmanneksi jakopisteiden kuutiot, saamme sen aikaan (riemastuttavan helposti):

  x=linspace(-1,1,10); x2=x.^2; x3=x.^3;
 taulukko=[x' x2' x3']

% pitemmän x-vektorin tapauksessa kannattaa katsoa
% osissa, tyyliin taulukko(1:5,:)

Huomaa, että vaakavektorista saadaan pystyvektori transponoimalla, eli operaatiolla x'

plot(x,x2,x,x3); grid;shg

plot(x,taulukko); grid;shg


6. For, while, if - and relations

In their basic forms, these MATLAB flow control statements operate like those in most computer languages.

For. For example, for a given n, the statement

        x = []; for i = 1:n, x=[x,i^2 ], end
or
        x = [];
        for i = 1:n
            x = [x,i^2 ]
        end
will produce a certain n-vector and the statement
        x = []; for i = n:-1:1, x=[x,i^2 ], end
will produce the same vector in reverse order. Try them.

Huom ! Tällaisia vektorin alkiotason silmukoita ei ole syytä suosia (ne ovat karkeaa pilaa, Matlabin väärinkäyttöä). Tietysti tuollainen hoidettaisiin edellä esitetyillä keinoilla. (Vektorin kääntämiseen takaperin on fliplr (left-right) ja ylösalaisin flipud (updown) .) No teepä !

Note that a matrix may be empty (such as x = []). The statements

        for i = 1:m
             for j = 1:n
                 H(i, j) = 1/(i+j-1);
             end
        end
        H
will produce and print to the screen the m-by-n hilbert matrix. The semicolon on the inner statement suppresses printing of unwanted intermediate results while the last H displays the final result.

Jos Matlabissa ei sattuisi olemaan komentoa hilb tai emme sitä muistaisi, niin yllä oleva muodostamistapa olisi ihan asiallinen (enkä sitä menisi tuomitsemaan alkiotason silmukoista huolimatta pilailuksi).

While. The general form of a while loop is

        while   relation
          statements
        end
The statements will be repeatedly executed as long as the relation remains true. For example, for a given number a, the following will compute and display the smallest nonnegative integer n such that 2n >=a:
        n = 0;
        while  2^n < a
             n = n + 1;
        end
        n
If. The general form of a simple if statement is
        if relation
          statements
        end
The statements will be executed only if the relation is true. Multiple branching is also possible, as is illustrated by
         if n < 0
              parity = 0;
         elseif  rem(n,2) == 0
              parity = 2;
         else
              parity = 1;
         end
In two-way branching the elseif portion would, of course, be omitted.

Relations. The relational operators in MATLAB are

         <      less than
         >      greater than
         <=     less than or equal
         >=     greater than or equal
         ==     equal
         ~=     not equal.
Note that "=" is used in an assignment statement while "==" is used in a relation. Relations may be connected or quantified by the logical operators
         &      and
         |      or
         ~      not.
When applied to scalars, a relation is actually the scalar 1 or 0 depending on whether the relation is true or false. Try 3 < 5, 3 > 5, 3 == 5, and 3 == 3. When applied to matrices of the same size, a relation is a matrix of 0's and 1's giving the value of the relation between corresponding entries. Try a = rand(5), b = triu(a), a == b.

A relation between matrices is interpreted by while and if to be true if each entry of the relation matrix is nonzero. Hence, if you wish to execute statement when matrices A and B are equal you could type

        if  A == B
            statement
        end
but if you wish to execute statement when A and B are not equal, you would type
        if any(any(A ~ B))    ** Tarkista, pitäiskö olla: A ~= B **
           statement
        end
or, more simply,
        if A == B else
           statement
        end
Note that the seemingly obvious
        if  A ~= B, statement, end
will not give what is intended since statement would execute only if each of the corresponding entries ofA and B differ. The functions any and all can be creatively used to reduce matrix relations to vectors or scalars. Two any's are required above since any is a vector operator (see section 8).

The for statement permits any matrix to be used instead of 1:n. See the User's Guide for details of how this feature expands the power of the for statement.


7. Scalar functions

Certain MATLAB functions operate essentially on scalars, but operate element-wise when applied to a matrix. Näin toimivat mm. kaikki matemaattiset perusfunktiot. Certain MATLAB functions operate essentially on scalars, but operate element-wise when applied to a matrix. Näin toimivat mm. kaikki matemaattiset perusfunktiot. Omat funktiot on useimmiten syytä kirjoittaa näin toimiviksi.

Jos f on skalaarifunktio, niin

       f(skalaari) -> skaalaari

               | f(a1 1) ...   f(a1 n)  |
               | f(a2 1) ...   f(a2 n)  |
       f(A) -> |         ...           |
               | f(am 1) ...   f(am n)  |
The most common such functions are
        sin    asin    exp                 abs       round
        cos    acos    log (natural log)   sqrt      floor
        tan    atan    rem (remainder)     sign      ceil

8. Vector functions

Other MATLAB functions operate essentially on a vector (row or column), but act on an m-by-n matrix (m>=2) in a column-by-column fashion to produce a row vector containing the results of their application to each column. Row-by-row action can be obtained by using the transpose; for example, mean(A')'.
     f(vekt) -> skal
     f(A)   operoi sarakkeittain:


               |        |     |           |
               | f(a. 1)   ...     f(a. n) |
       f(A) -> |        |     |           |
               |        |     |           |




A few of these functions are
        max        sum       median     any   floor
        min        prod      mean       all   ceil   round
        sort       std
For example, the maximum entry in a matrix A is given by max(max(A)) rather than max(A). Try it.

Matriisin jonoutus pitkäksi sarakevektoriksi saadaan aikaan kirjoittamalla

         A(:)
Niinpä matriisin A suurin alkio saadaan myös näin: max(A(:)) . Kokeile tätäkin.

Jonoutetusta pitkästä vektorista päästään takaisin matriisiin komennolla reshape , joka on varsin kätevä moneen hommaan, katso helpwin reshape .

Tehtävä: (a) Kirjoita lauseke, joka laskee matriisin A alkioiden itseisarvojen sarakesummien maksimin.
(b) Sama rivisummille.
Edellinen on matriisin ns. 1-normi, jälkimmäinen taas "ääretön-normi", näistä enemmän tuonnempana.


9. Matrix functions

Much of MATLAB's power comes from its matrix functions. Matriisifunktion argumenttina on matriisi (joissakin tapauksessa kelpaa vain neliömatriisi). Tuloksena saattaa olla oikeastaan mitä vain, kuten Some of the most useful ones are
        eig         eigenvalues and eigenvectors
        chol        cholesky factorization
        svd         singular value decomposition
        inv         inverse
        lu          LU factorization
        qr          QR factorization
        hess        hessenberg form
        schur       schur decomposition
        rref        reduced row echelon form
        expm        matrix exponential
        sqrtm       matrix square root
        poly        characteristic polynomial
        det         determinant
        size        size
        norm        1-norm, 2-norm, F-norm, infinity-norm
        cond        condition number in the 2-norm
        rank        rank
MATLAB functions may have single or multiple output arguments. For example,
        y = eig(A)     or simply      eig(A)
produces a column vector containing the eigenvalues of A while
        [U,D] = eig(A)
produces a matrix U whose columns are the eigenvectors of A and a diagonal matrix D with the eigenvalues of A on its diagonal. Try it.

Tehtävä: Muodosta symmetrinen 10 x 10 satunnaismatriisi (käyttäen rand -funktiota), nimeltään A. Huomaa, että symmetrisen matriisin saat esim. kertomalla mielivaltaisen matriisin ja sen transpoosin keskenään. Muodosta matriisit V ja D, missä V:n sarakkeet ovat A:n ominaisvektorit ja D:n diagonaalialkiot ovat A:n ominaisarvot. Laske A*V ja V*D ja totea ne samoiksi. Muistele ominaisarvojen ja - vektoreiden määritelmää ja perustele, miksi näin on.


10. Esimerkkejä nuolinäppäiniteroinnista

"Köyhän miehen työarkin" piirteitä:

The command line in MATLAB can be easily edited. The cursor can be positioned with the left/right arrows and the Backspace (or Delete) key used to delete the character to the left of the cursor. Other editing features are also available. On a PC try the Home, End, and Delete keys;

UNIX:ssa toimivat Emacs-tyyliset (tcshell-tyyliset) CTR-A (alkuun, "Anfang"), CTR-E (loppuun, "Ende"), CTR-K (rivin lopun poisto "kill").

A convenient feature is use of the up/down arrows to scroll through the stack of previous commands. One can, therefore, recall a previous command line, edit it, and execute the revised command line. For small routines, this is convenient. Muista kuitenkin aina pitää editori-ikkuna työssä mukana (pienestä alusta kehittyy usein isompaa). (see sections 12 and 14). For example, flopcounts (see section 15) for computing the inverse of matrices of various sizes could be compared by repeatedly recalling, editing, and executing

        a = rand(8,8); flops(0), inv(a); flops
If one wanted to compare plots of the functions y = sin mx and y = sin nx on the interval [0,2*pi] for various m and n, one might do the same for the command line:
        m=2; n=3; x=0:.01:2*pi; y=sin(m*x); z=cos(n*x); plot(x,y,x,z)

Esimerkki nuolinäppäinalgoritmista, Pika-Newton

"Köyhyydestä" huolimatta Matlab-ikkunassa voidaan pystyttää pikaisesti ihan merkittäviä on-line alhgoritmeja suorittamalla iteraatiota nuolinäppäimellä. Tarvittaessa kannattaa venyttää Matlab-ikkuna leveäksi, jotta saadaan pitkä (tarvittaessa pari pitkää riviä) algoritmin ytimeksi. Tätä toimintaa kannattaa suunnitella yhdessä editori-ikkunan kanssa (muista myös kynä ja paperi!)

Esim: Ratkaise f(x)=0 Newtonin menetelmällä , kun f(x)=x*exp(-x)-sin(5*x) Verrataan vielä kuvaan zoomaamalla.

x=linspace(0,5);y=x.*exp(-x)-sin(5*x);plot(x,y);grid;shg

Lasketaan derivaatta Maplella:

    |\^/|     Maple V Release 5.1 (Helsinki University of Technology)
._|\|   |/|_. Copyright (c) 1981-1998 by Waterloo Maple Inc. All rights
 \  MAPLE  /  reserved. Maple and Maple V are registered trademarks of
 <____ ____>  Waterloo Maple Inc.
      |       Type ? for help.
> diff(x*exp(-x)-sin(5*x),x);
                       exp(-x) - x exp(-x) - 5 cos(5 x)


%Valitaan kuvasta alkupiste 1.3.

x=1.3;
fx=x.*exp(-x)-sin(5*x);dfx=exp(-x)-x.*exp(-x)-5*cos(5*x);x=x-fx./dfx

Usean muuttujan Newton

Esim:
 1+x2-y2+excos y = 0
 2 x y + ex sin y = 0
Piirretään ensin:
clf
x=linspace(-2,5,40);y=linspace(-6,6,40);
[X,Y]=meshgrid(x,y);            
Z1=1+X.^2-Y.^2+exp(X).*cos(Y);
Z2=2*X.*Y+exp(X).*sin(Y);
contour(X,Y,Z1,[0 0])
hold on
contour(X,Y,Z2,[0 0],'r')
shg
figure
surfl(X,Y,Z1);hold on; surfc(X,Y,Z2);colorbar;shg;grid

%%%%%%% funjac.m %%%%%%%%%%%%
function [f,J]=funjac(x)
% Kutsuesim: [f,J]=funjac([1,2])  % Lasketaan funktio ja Jakobiaani pist [1,2].
% Tämä on algoritmin ongelmariippuva osa, käytä tarvittaessa Maplea
% Jakobiaanin muodostamiseen

function [f,J]=funjac(x)
% Kutsuesim: [f,J]=funjac([1,2])  % Lasketaan funktio ja Jakobiaani pist [1,2].
% Tämä on algoritmin ongelmariippuva osa, käytä tarvittaessa Maplea
% Jakobiaanin muodostamiseen

f=[1+x(1)^2-x(2)^2+exp(x(1))*cos(x(2)); 2*x(1)*x(2)+exp(x(1))*sin(x(2))];
J=[2*x(1) + exp(x(1))*cos(x(2)),  -2*x(2) - exp(x(1))*sin(x(2))
   2*x(2) + exp(x(1))*sin(x(2)),   2*x(1) + exp(x(1))*cos(x(2))];

%%%%%%%%% end funjac.m %%%%%%%%%%%%%%%%%%%%%%%%%

 \  MAPLE  /  reserved. Maple and Maple V are registered trademarks of
 <____ ____>  Waterloo Maple Inc.
      |       Type ? for help.
> with(linalg):
> jacobian([1+x^2-y^2+exp(x)*cos(y),2*x*y+exp(x)*sin(y)],[x,y]);
                 [2 x + exp(x) cos(y)    -2 y - exp(x) sin(y)]
                 [                                           ]
                 [2 y + exp(x) sin(y)    2 x + exp(x) cos(y) ]


Sitten iteroidaan:
x=[1;-2];
[fx,Jx]=funjac(x);h=-Jx\fx;x=x+h

Tai vaikka:

x=ginput
x=x'
[fx,Jx]=funjac(x);h=-Jx\fx;x=x+h


Esimerkki nuolinäppäinalgoritmista, Euler

format compact
f=inline('t.^2-y','t','y')

clf;hold on, grid, title('dy/dt=t^2-y'); n=2;a=0;b=4;ya=1;
[T,Y]=euleri(f,a,b,ya,n);plot(T,Y,T,Y,'o'); shg;[T',Y'], n=2*n

%%%%%% euleri.m %%%%%%%%%%%%
function [T,Y]=euleri(f,a,b,ya,n)
h=(b-a)/n;
Y=zeros(1,n+1);T=Y;
T(1)=a;Y(1)=ya;
for j=1:n
   Y(j+1)=Y(j)+h*feval(f,T(j),Y(j));
   T(j+1)=a+j*h;
end;   
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

11. Submatrices and colon notation

Näistä jo puhuttiin osittain, mutta kertaus ...

Vectors and submatrices are often used in MATLAB to achieve fairly complex data manipulation effects. Colon notation" (which is used both to generate vectors and reference submatrices) and subscripting by vectors are keys to efficient manipulation of these objects. Creative use of these features permits one to minimize the use of loops (which slows MATLAB) and to make code simple and readable. Special effort should be made to become familiar with them.

The expression 1:5 (met earlier in for statements) is actually the row vector [1 2 3 4 5]. The numbers need not be integers nor the increment one. For example,

        0.2:0.2:1.2
gives [0.2, 0.4, 0.6, 0.8, 1.0, 1.2], and
        5:-1:1  gives   [5 4 3 2 1].
The following statements will, for example, generate a table of sines. Try it.
        x = [0.0:0.1:2.0]' ;
        y = sin(x);
        [x y]
Note that since sin operates entry-wise, it produces a vector y from the vector x.

The colon notation can be used to access submatrices of a matrix. For example,

A(1:4,3) is the column vector consisting of the first four entries of the third column of A.
A colon by itself denotes an entire row or column:
A(:,3) is the third column of A , and A(1:4,:) is the first four rows.
Arbitrary integral vectors can be used as subscripts:
A(:,[2 4]) contains as columns, columns 2 and 4 of A .
Such subscripting can be used on both sides of an assignment statement:
A(:,[2 4 5]) = B(:,1:3) replaces columns 2,4,5 of A with the first three columns of B. Note that the entire altered matrix A is printed and assigned. Try it.
Columns 2 and 4 of A can be multiplied on the right by the 2-by-2 matrix [1 2;3 4]:
A(:,[2,4]) = A(:,[2,4])*[1 2;3 4]
Once again, the entire altered matrix is printed and assigned.

If x is an n-vector, what is the effect of the statement x = x(n:-1:1)? Try it.

To appreciate the usefulness of these features, compare these MATLAB statements with a Pascal, FORTRAN, or C routine to effect the same.


12. M-files

MATLAB can execute a sequence of statements stored on diskfiles. Such files are called M-files" because they must have the file type of .m" as the last part of their filename. Much of your work with MATLAB will be in creating and refining M-files.

There are two types of M-files: script files and function files.

Script files. A script file consists of a sequence of normal MATLAB statements. If the file has the filename, say, rotate.m, then the MATLAB command rotate will cause the statements in the file to be executed. Variables in a script file are global and will change the value of variables of the same name in the environment of the current MATLAB session.

Script files are often used to enter data into a large matrix; in such a file, entry errors can be easily edited out. If, for example, one enters in a diskfile data.m

        A = [
        1 2 3 4
        5 6 7 8
        ];
then the MATLAB statement data will cause the assignment given in data.m to be carried out.

An M-file can reference other M-files, including referencing itself recursively.

Function files. Function files provide extensibility to MATLAB. You can create new functions specific to your problem which will then have the same status as other MATLAB functions. Variables in a function file are by default local. However, version 4.0 (nyt on jo 5.3) permits a variable to be declared global.

We first illustrate with a simple example of a function file. Otetaan pari vielä yksinkertaisempaa. Määritellään funktio 'sincos', joka laskee sinin ja cosinin tulon.

function y=sincos(x)
y=sin(x).*cos(x);

Huomaa vektorointi .*-kertolaskulla. (Muuten emme voisi edes piirtää alla olevalla standarditavalla.) Huom! Uusissa Matlabin versioissa tällaiset pikku funktiot voidaan myös määritellä suoraan Matlab-istunnossa:

sincos=inline('sin(x).*cos(x)','x');

Piirretään

x=linspace(0,2*pi);
plot(x,sincos(x)); shg
Sitten kaksi tulosarvoa palauttava pikku esimerkki.
function [mean,stdev] = stat(x)
            % Keskeisiä tilastollisia tunnuslukuja
            % x - vektori
            % esim: [ke,std]=stat(1:10)
            n = length(x);
            mean = sum(x) / n;
            stdev = sqrt(sum((x - mean).^2)/n);

        function  a = randint(m,n)
        %RANDINT  Randomly generated integral matrix.
        %         randint(m,n) returns an m-by-n such matrix with entries
        %         between 0 and 9.
        a = floor(10*rand(m,n));
A more general version of this function is the following:
        function  a = randint(m,n,a,b)
        %RANDINT  Randomly generated integral matrix.
        %         randint(m,n) returns an m-by-n such matrix with entries
        %         between 0 and 9.
        %         rand(m,n,a,b) return entries between integers  a  and  b .
        if nargin < 3, a = 0; b = 9; end
        a = floor((b-a+1)*rand(m,n)) + a;
This should be placed in a diskfile with filename randint.m (corresponding to the function name). The first line declares the function name, input arguments, and output arguments; without this line the file would be a script file. Then a MATLAB statement z = randint(4,5), for example, will cause the numbers 4 and 5 to be passed to the variables a and b in the function file with the output result being passed out to the variable z. Since variables in a function file are local, their names are independent of those in the current MATLAB environment.

Note that use of nargin ("number of input arguments") permits one to set a default value of an omitted input variable-such as a and b in the example.

Tehtävä Kirjoita tämä tiedostoon randint.m (Voit leikata/liimata tästä suoraan, onhan sinulla emacs auki!) (Tietysti UNIX:ssa näinkin: Hiiren vasen, maalaus, cat > randint.m, hiiren keskimmäinen, CTR-D). Kokeile help randint ja testaa.

Kehitetään yllä oleva stat-funktio tomimaan vektorifunktioiden tavoin, jos syötteenä on matriisi, siis saraketyyliin, kuten sum, max jne.

        function  [mean, stdev] = stat(x)
        % STAT  Mean and standard deviation
        %      For a vector x, stat(x) returns the
        %      mean and standard deviation of  x.
        %      For a matrix x, stat(x) returns two row vectors containing,
        %      respectively, the mean and standard deviation of each column.
        [m  n] = size(x);
        if m == 1
              m = n;     % handle case of a row vector
        end
        mean = sum(x)/m;
        stdev = sqrt(sum(x.^ 2)/m - mean.^2);
Once this is placed in a diskfile stat.m, a MATLAB command [xm, xd] = stat(x), for example, will assign the mean and standard deviation of the entries in the vector x to m and xd, respectively. Single assignments can also be made with a function having multiple output arguments. For example, xm = stat(x) (no brackets needed around xm) will assign the mean of x to xm.

The % symbol indicates that the rest of the line is a comment; MATLAB will ignore the rest of the line. However, the first few comment lines, which document the M-file, are available to the on-line help facility and will be displayed if, for example, help stat is entered. Such documentation should always be included in a function file.

This function illustrates some of the MATLAB features that can be used to produce efficient code. Note, for example, that x.^2 is the matrix of squares of the entries of x, that sum is a vector function (section 8), that sqrt is a scalar function (section 7), and that the division in sum(x)/m is a matrix-scalar operation.

The following function, which gives the greatest common divisor of two integers via the Euclidean algorithm, illustrates the use of an error message (see the next section).

        function  a = gcd(a,b)
        % GCD  Greatest common divisor
        %      gcd(a,b) is the greatest common divisor of
        %      the integers a and b, not both zero.
        a = round(abs(a));  b = round(abs(b));
        if  a == 0 & b == 0
            error('The gcd is not defined when both numbers are zero')
        else
            while b  ~= 0
                r = rem(a,b);
                a = b;  b = r;
            end
        end
Some more advanced features are illustrated by the following function. As noted earlier, some of the input arguments of a function-such as tol in the example, may be made optional through use of nargin ("number of input arguments"). The variable nargout can be similarly used. Note that the fact that a relation is a number (1 when true; 0 when false) is used and that, when while or if evaluates a relation, "nonzero" means "true" and 0 means "false". Finally, the MATLAB function feval permits one to have as an input variable a string naming another function.
        function  [b, steps] = bisect(fun, x, tol)
        %BISECT Zero of a function of one variable via the bisection method.
        %         bisect(fun,x) returns a zero of the function.  fun is a string
        %         containing the name of a real-valued function of a single
        %         real variable; ordinarily functions are defined in M-files.
        %         x  is a starting guess.  The value returned is near a point
        %         where  fun  changes sign.  For example,
        %         bisect('sin',3) is pi.  Note the quotes around sin.
        %
        %         An optional third input argument sets a tolerence for the
        %         relative accuracy of the result.  The default is eps.
        %         An optional second output argument gives a matrix containing a
        %         trace of the steps; the rows are of form  [c f(c)].

        % Initialization
        if nargin < 3, tol = eps; end
        trace = (nargout == 2);
        if x  ~= 0, dx = x/20; else, dx = 1/20; end
        a = x - dx;  fa = feval(fun,a);
        b = x + dx;  fb = feval(fun,b);

        % Find change of sign.
        while (fa > 0) == (fb > 0)
             dx = 2.0*dx;
             a = x - dx;  fa = feval(fun,a);
             if (fa > 0) ~= (fb > 0), break, end
             b = x + dx;  fb = feval(fun,b);
        end
        if trace, steps = [a fa; b fb]; end

        % Main loop
        while  abs(b - a) > 2.0*tol*max(abs(b),1.0)
             c = a + 0.5*(b - a);  fc = feval(fun,c);
             if trace, steps = [steps; [c fc]]; end
             if (fb > 0) == (fc > 0)
                  b = c;  fb = fc;
               else
                 a = c;  fa = fc;
             end
        end
Some of MATLAB's functions are built-in while others are distributed as M-files. The actual listing of any M-file-MATLAB's or your own-can be viewed with the MATLAB command type functionname. Try entering type eig, type vander, and type rank.

Opettavaista katsoa, miten "isot pojat/tytöt" Mathworks:ssa ovat funktioita kirjoitelleet. Sama pätee Mapleen (Maplesoft).


13. Text strings, error messages, input

Text strings are entered into MATLAB surrounded by single quotes. For example,
        s = 'This is a test'
assigns the given text string to the variable s.

Text strings can be displayed with the function disp. For example:

        disp('this message is hereby displayed')
Error messages are best displayed with the function error
        error('Sorry, the matrix must be symmetric')
since when placed in an M-File, it causes execution to exit the M-file.

In an M-file the user can be prompted to interactively enter input data with the function input. When, for example, the statement

        iter = input('Enter the number of iterations:  ')
is encountered, the prompt message is displayed and execution pauses while the user keys in the input data. Upon pressing the return key, the data is assigned to the variable iter and execution resumes.


14. Managing M-files, Matlab environment

As noted in section 1, on systems permitting multiple processes, such as one running Unix, it may be preferable to keep both MATLAB and your local editor active, keeping one process suspended while working in the other. (CTR-Z bg , takaisin Matlabiin: fg )

If these processes can be run in multiple windows, as on a workstation, you will want to keep MATLAB active in one window and your editor active in another. YES, INDEED !

Version 4.0 has many debbugging tools (even more in 5.3). See help dbtype and references given there.

Matlabin tuntemia UNIX/Dos-komentoja
When in MATLAB, the command dir will list the contents of the current directory while the command what will list only the M-files in the directory. The MATLAB commands delete and type can be used to delete a diskfile and print a file to the screen, respectively, and chdir can be used to change the working directory. Myös pwd. While these commands may duplicate system commands, they avoid the use of an !. Siis huutomerkillä voidaan antaa muitakin käyttis- komentoja (mikä ei ole useinkaan tarpeen, kun on niitä ikkunoita).

M-files must be accessible to MATLAB. On most mainframe or workstation network installations, personal M-files which are stored in a subdirectory of one's home directory named matlab will be accessible to MATLAB from any directory in which one is working. See the discussion of MATLABPATH in the User's Guide for further information.


15. Comparing efficiency of algorithms: flops and (etime) tic/toc

Two measures of the efficiency of an algorithm are the number of floating point operations (flops) performed and the elapsed time.

The MATLAB function flops keeps a running total of the flops performed. The command flops(0) (not flops = 0!) will reset flops to 0. Hence, entering flops(0) immediately before executing an algorithm and flops immediately after gives the flop count for the algorithm.

tic ja toc, esim:

   A=rand(100,100);b=ones(100,1); tic; x = A \ b;  toc


16. Output format

While all computations in MATLAB are performed in double precision, the format of the displayed output can be controlled by the following commands.
        format short     fixed point with 4 decimal places (the default)
        format long      fixed point with 14 decimal places
        format short e   scientific notation with 4 decimal places
        format long e    scientific notation with 15 decimal places
Once invoked, the chosen format remains in effect until changed.

The command format compact will suppress most blank lines allowing more information to be placed on the screen or page. It is independent of the other format commands.


17. Hardcopy

Hardcopy is most easily obtained with the diary command. The command
        diary  filename 
causes what appears subsequently on the screen (except graphics) to be written to the named diskfile (if the filename is omitted it will be written to a default file named diary) until one gives the command diary off; the command diary on will cause writing to the file to resume, etc. When finished, you can edit the file as desired and print it out on the local system.


18. Graphics

Kts. myös [SKK] 2.8. ss. 21 - 22.

MATLAB can produce both planar plots and 3-D mesh surface plots. To preview some of these capabilities in version 3.5, enter the command plotdemo.

Planar plots. The plot command creates linear x-y plots; if x and y are vectors of the same length, the command plot(x,y) opens a graphics window and draws an x-y plot of the elements of x versus the elements of y. You can, for example, draw the graph of the sine function over the interval -4 to 4 with the following commands:

        x = -4:.01:4;  y = sin(x);  plot(x,y)
Try it. The vector x is a partition of the domain with meshsize 0.01 while y is a vector giving the values of sine at the nodes of this partition (recall that sin operates entrywise).

Kuten edellä oli puhe, usein linspace voi olla kätevämpikin (saadaan aina 100:aan osaan jako, jos käytetään oletusarvoa). Siis edellä olisi yhtä hyvin voitu kirjoittaa:

         x=linspace(-4,4);
plot-funktion toiminnasta saa havainnollisen kuvan ottamalla harvan diskretoinnin. Kokeile vaikka näin:
       x=linspace(-4,4,10); y=sin(x); [x' y'], plot(x,y)
Varmista, että ymmärrät kaiken, kiinnitä myös huomiota puolipisteisiin ja pilkkuun, tässä on kaikki harkittua. Huomaa, että Matlabin nuolinäppäineditointityylillä on kätevää operoida, kun kirjoitetaan pitkiä rivejä. Tässäkin tarvitaan vain yksi nuolipainallus, jonka jälkeen voidaan esim. diskretointimäärää käydä muuttamassa ja lähettää rivi uudelleen suoritukseen.

Tehtävä Piirrä funktion x3-2x +1 kuvaaja välillä [-2,2] punaisella värillä.

As a second example, you can draw the graph of y=e-x^2 over the interval -1.5 to 1.5 as follows:

        x = -1.5:.01:1.5;  y = exp(-x.^2);  plot(x,y)
Note that one must precede the power-to sign by a period to ensure that it operates entrywise (see section 3).

Parametrimuodossa annetut käyrät

Plots of parametrically defined curves can also be made. Try, for example,

        t=0:.001:2*pi; x=cos(3*t); y=sin(2*t); plot(x,y)
Ennen tätä kannattaa kokeilla kaikkein perustavanlaatuisinta, eli yksikköympyrää (piirrämme oikeastaan 100-kulmion):
   t=linspace(0,2*pi);x=cos(t);y=sin(t);plot(x,y);
   axis('equal');axis('square')
Vertaa tätä kuvaan
   t=linspace(0,2*pi);x=cos(t);y=sin(t);plot(t,x,'r',t,y,'b');
Ymmärräthän nyt varmasti! Vrt. Maplen parametripiirto, harj0.mws , [HAM] s. 93

The command grid will place grid lines on the current graph. Kannattaa käyttää !

Käyrä avaruudessa
Teemme tässä pienen sivuhyppäyksen avaruuteen, koska avaruuskäyrä yleistää ilmeisellä tavalla parametrimuodossa annetun tasokäyrän. Avaruuskäyrälle luonnollisin esitys on parametrimuoto [x(t),y(t),z(t)] . Piirto tapahtuu komennolla plot3

Jos ympyrä on perusparametrikäyrä tasossa, niin ruuviviiva on sitä avarudessa.

   t=linspace(0,4*pi);x=cox(t);y=sin(t);z=t;
   plot3(x,y,z);    % Ruuviviiva
Napakoordinaatistossa annettu käyrä r(fii) voidaan piirtää plot-komennolla tyyliin
    fii=linspace(fii1,fii2);x=r(fii).*cos(fii);y=r(fii).*sin(fii);
    plot(x,y);
    axis('equal');axis('square');grid  % Usein näissä halutaan sama
                                       % skaala akseleille
Matlabissa on myös funktio polar , jossa napakoordinaattimuunnos on sisäänrakennettu. Sitä käyttäen voidaan piirtää suoraan näin:
    fii=linspace(fii1,fii2);polar(fii,r(fii));
    grid  % Lisäbonuksena saadaan myös hilaviivat napakoordinaattiviivoina
Lisää napakoordinaattiesim. [BB] s. 53 -> ja sec 10.3 ja exe 10.1, 10.3 The graphs can be given titles, axes labeled, and text placed within the graph with the following commands which take a string as an argument.
        title         graph title
        xlabel        x-axis label
        ylabel        y-axis label
        gtext         interactively-positioned text
        text          position text at specified coordinates
For example, the command
        title('Best Least Squares Fit')
gives a graph a title. The command gtext('The Spot') allows a mouse or the arrow keys to position a crosshair on the graph, at which the text will be placed when any key is pressed. Tämäkin voidaan nykyisin hoitaa kuvaikkunan valikosta.

By default, the axes are auto-scaled. This can be overridden by the command axis. If c=[xmin,xmax,ymin,ymax] is a 4-element vector, then axis(c) sets the axis scaling to the precribed limits. By itself, axis freezes the current scaling for subsequent graphs; entering axis again returns to auto-scaling. The command axis('square') ensures that the same scale is used on both axes. In version 4.0, axis has been significantly changed; see help axis.

Two ways to make multiple plots on a single graph are illustrated by

        x=0:.01:2*pi;y1=sin(x);y2=sin(2*x);
        y3=sin(4*x);plot(x,y1,x,y2,x,y3)
and by forming a matrix Y containing the functional values as columns
        x=0:.01:2*pi; Y=[sin(x)', sin(2*x)', sin(4*x)']; plot(x,Y)
Another way is with hold. The command hold freezes the current graphics screen so that subsequent plots are superimposed on it. Entering hold again releases the "hold." The commands hold on and hold off are also available in version 4.0.

One can override the default linetypes and pointtypes. For example,

        x=0:.01:2*pi; y1=sin(x); y2=sin(2*x); y3=sin(4*x);
        plot(x,y1,'--',x,y2,':',x,y3,'+')
        plot(x,y1,'--b',x,y2,'g',x,y3,'+y')
renders a dashed line and dotted line for the first two graphs while for the third the symbol is placed at each node. The line- and mark-types are
Linetypes: solid (-), dashed (-). dotted (:), dashdot (-.)

Marktypes: point (.), plus (+), star (*), circle (o), x-mark (x)

See help plot for line and mark colors.

Viimeisellä rivillä lisättiin vielä värimääreet (lisää help plot, help color).

'b' - blue, 'g' - green, 'y' - yellow
The command subplot can be used to partition the screen so that up to four plots can be viewed simultaneously. See help subplot.
Graphics hardcopy, kuvan editointi
A hardcopy of the graphics screen can be most easily obtained with the MATLAB command print. It will send a high-resolution copy of the current graphics screen to the printer, placing the graph on the top half of the page.

Kuva voidaan myös tulostaa tiedostoon monissa eri muodoissa, kuten eps, gif, jpeg, ym. Voidaan käyttää print-komennon valitsimia tai tulostaa suoraan grafiikkaikkunan valikosta. Versiossa 5.3 on mahdollisuus myös editoida kuvaa piirtämällä siihen viivoja, lisäämällä tekstiä ym. Valikko selittää itse itsensä.

Piirtoikkunat, figure, clf, shg

Grafiikkakomento (kuten plot) avaa ikkunan numero 1. Jos halutaan ohjata grafiikka uuteen ikkunaan, komennetaan figure tai figure(n). Aiemmin avattuihin ikkunoihin päästään käsiksi komenttamalla vaikkapa figure(1) , jolloin voidaan jatkaa piirtämistä ensimmäiseen ikkunaan, arvatenkin käytteän hyväksi hold on komentoa, tai voidaan editoida kuvaa, tulostaa se, ym.

3-D mesh plots. Three dimensional mesh surface plots are drawn with the function mesh. The command mesh(z) creates a three-dimensional perspective plot of the elements of the matrix z. The mesh surface is defined by the z-coordinates of points above a rectangular grid in the x-y plane. Try mesh(eye(10)).

To draw the graph of a function z=f(x,y) over a rectangle, one first defines vectors x and y which give partitions of the sides of the rectangle. With the function meshgrid one then creates a matrix X, each row of which equals x and whose column length is the length of y, and similarly a matrix Y, each column of which equals y, as follows:

        [X,Y] = meshgrid(x,y);
One then computes a matrix Z, obtained by evaluating f entrywise over the matrices X and Y, to which mesh can be applied.

You can, for example, draw the graph of z=e-x^2-y^2 over the square [-2,2] x [-2,2] as follows (try it):

        x = -2:.1:2;
        y = x;
        [X,Y] = meshgrid(x,y);
        Z = exp(-X.^2 - Y.^2);
        mesh(x,y,Z)  % yhtä hyvin mesh(X,Y,Z)
You are referred to the User's Guide for further details regarding mesh.

Lisää [BB] s. 54 ->

Kts. myös surf, surfc, contour, waterfall, etc.
In version 4.0, the 3-D graphics capabilities of MATLAB have been considerably expanded. Consult the on-line help for plot3, mesh, and surf.

Katselusuuntaa voi säädellä view-komennolla ja versiossa 5.3 voi kuvaa pyöritellä myös grafiikkaikkunan valikosta hiiren avulla. (Ei ihan niin hienosti kuin Maplessa mutta toisaalta grafiikka on Matlabissa paljon nopeampaa.)

Jatketaan vielä yllä olevaa esimerkkiä piirtämällä vierekkäin pintakuva ja korkeuskäyrät, lisätään tekstejä:

        subplot(1,2,1),surfc(x,y,Z)  
        title('Pintapiirros')
        subplot(1,2,2),contour(x,y,Z)
        title('Korkeuskäyrät')
Funktion piirto, fplot
Matlab-työskentelyssä on olennaisen tärkeää totutella omian funktioiden kirjoittamiseen. (Muistimmekohan sitä tarpeeksi edellä korostaa.) Jos olemme kirjoittaneet (tai jos Mathworks tai joku muu on) funktion tiedostoon f.m , voimme tietysti piirtää :
    x=linspace(a,b);plot(x,f(x))
Hieman vaivattomammin voimme tehdä näin
   fplot('f',[a,b])
Tämä vastaa läheisemmin sitä tapaa, jota esim. Maplen plot noudattaa. (Käyttäjän ei tarvitse huolehtia diskretoinnista.)

Kokeile nyt aluksi vaikka fplot('log',[0.5,2])

Tehtävä Piirrä fplot:n avulla funktion f(x)=e-x2 sin(x)/x kuvaaja erilaisilla väleillä.


20. Uudet tietorakenteet

Tämä on sekavassa tilassa ...

Solumatriisit (Cell Matrices)

EvA s. 109 ->
A={'Otsikko';[1 2;3 4];magic(10)}
A
celldisp(A)
cellplot(A)
A{1,1},A{2,1},A{3,1}
%% ei toimi näin: %[ots,ykakone,taika10]=deal([A{1,1},A{2,1},A{3,1}])
A={'Otsikko';{1 2;3 4};magic(10)}

A
celldisp(A)
cellplot(A)

clear
AA={'A';magic(3)}
nimi=AA{1}
A=AA{2}

clear
M=magic(4)
A.nimi='M'
A.data=M
A2.nimi='A2'
A2.data=A.data^2

for i=1:5
nimet{i}=['nimi',num2str(i)]
  end;
 cellplot(nimet);shg


Data Analysis and Statistics

A(:,:,1)=[1 2 3;-2 3 -1;5 -4 -1];A(:,:,2)=vander(1:3);

A(:,:,1) =
     1     2     3
    -2     3    -1
     5    -4    -1
A(:,:,2) =
     1     1     1
     4     2     1
     9     3     1
» max(A)
ans(:,:,1) =
     5     3     3
ans(:,:,2) =
     9     3     1
» min(A)
ans(:,:,1) =
    -2    -4    -1
ans(:,:,2) =
     1     1     1

» whos
  Name      Size         Bytes  Class

  A         3x3x2          144  double array   % 3 riviä, 3 saraketta, 2 tasoa
  ans       1x3x2           48  double array

min(min(A))

ans(:,:,1) =
    -4
ans(:,:,2) =
     1
» min(min(min(A)))
ans =
    -4
» min(A(:))
ans =
    -4

A
sum(A)
A(:,:,1) =
     1     2     3
    -2     3    -1
     5    -4    -1
A(:,:,2) =
     1     1     1
     4     2     1
     9     3     1
ans(:,:,1) =
     4     1     1     % 1. tason sarakesummat
ans(:,:,2) =
    14     6     3     % 2. tason sarakesummat

cumsum(A)
ans(:,:,1) =
     1     2     3   % 1. tason sarakkeittain otetut kumulatiiviset summat
    -1     5     2
     4     1     1
ans(:,:,2) =
     1     1     1   % 2. tason sarakkeittain otetut kumulatiiviset summat
     5     3     2
    14     6     3
Vastaavasti: prod, cumprod

Tilastollisia funktioita

mean, median, std, cov, corrcoef hist, bar, stairs, stem, pareto, pie Jätetään ...
format compact
x=[1 1 3 4 5 1 9 8]
[m,y]=hist(x,10)  % Oletusarvo 10, toimii siten muodossa hist(x). 
bar(y,m)

Uudet tietorakenteet

Handbook s. 437

Aika havainnollinen esim. talosta, jossa 3 kerrosta, ... s. 437-8.

house=ceil(10*rand(3,3,3,4))
A=cell(3,4)
for i=1:3
   for j=1:4
     A{i,j}=ceil(10*rand(3,3));
   end;
end;

celldisp(A)
cellplot(A)

colspace

>> help colspace

 --- help for sym/colspace.m ---

 COLSPACE Basis for column space.
    The columns of B = COLSPACE(A) form a basis for the column space of A.
    SIZE(B,2) is the rank of A.
 
    Example:
 
      colspace(sym(magic(4))) is
 
        [  0,  1,  0]
        [  0,  0,  1]
        [  1,  0,  0]
        [ -3,  1,  3]
 
    See also NULL.


20. Reference

There are many MATLAB features which cannot be included in these introductory notes. Listed below are some of the MATLAB functions and operators available, grouped by subject area (Source: MATLAB User's Guide, version 3.5). Use the on-line help facility or consult the User's Guide for more detailed information on the functions.

There are many functions beyond these. There exist, in particular, several "toolboxes" of functions for specific areas; included among such are signal processing, control systems, robust-control, system identification, optimization, splines, chemometrics, mu-analysis and synthesis, state-space identification, and neural networks. (The toolboxes, which are optional, may not be installed on your system.) These can be explored via the command help.

General

   help        help facility
   demo        run demonstrations
   who         list variables in memory
   what        list M-files on disk
   size        row and column dimensions
   length      vector length
   clear       clear workspace
   computer    type of computer
   ^C          local abort
   exit        exit MATLAB
   quit        same as exit


Matrix/Array Operators

   Matrix Operators               Array Operators
   ---------------------------------------------------
   +    addition                  +    addition
   -    subtraction               -    subtraction
   *    multiplication            .*   multiplication
   /    right division            ./   right division
   \    left division             .\   left division
   ^    power                     .^   power
   '    conjugate transpose       .'   transpose


Relational and Logical Operators

   <           less than
   <=          less than or equal
   >           greater than
   >=          greater than or equal
   ==          equal
   ~=          not equal
   &           and
   |           or
   ~           not


Special Characters

   =           assignment statement
   [           used to form vectors and matrices
   ]           see [
   (           arithmetic expression precedence
   )           see (
   .           decimal point
   ...         continue statement to next line
   ,           separate subscripts and function arguments
   ;           end rows, suppress printing
   %           comments
   :           subscripting, vector generation
   !           execute operating system command


Special Values

   ans         answer when expression not assigned
   eps         floating point precision
   pi          pi
   i, j        sqrt(-1)
   inf         infinity
   NaN         Not-a-Number
   clock       wall clock
   date        date
   flops       floating point operation count
   nargin      number of function input arguments
   nargout     number of function output arguments
   tic, toc

Disk Files

   chdir       change current directory
   delete      delete file
   diary       diary of the session
   dir         directory of files on disk
   load        load variables from file
   save        save variables to file
   type        list function or file
   what        show M-files on disk
   fprintf     write to a file
   pack        compact memory via save


Special Matrices

   compan      companion
   diag        diagonal
   eye         identity
   gallery     esoteric
   hadamard    Hadamard
   hankel      Hankel
   hilb        Hilbert
   invhilb     inverse Hilbert
   linspace    linearly spaced vectors
   logspace    logarithmically spaced vectors
   magic       magic square
   meshgrid    domain for mesh points
   ones        constant
   pascal      Pascal
   rand        random elements
   toeplitz    Toeplitz
   vander      Vandermonde
   zeros       zero


Matrix Manipulation

   rot90       rotation
   fliplr      flip matrix left-to-right
   flipud      flip matrix up-to-down
   diag        diagonal matrices
   tril        lower triangular part
   triu        upper triangular part
   reshape     reshape
   .'          transpose
   :           convert matrix to single column; A(:)


Relational and Logical Functions

   any         logical conditions
   all         logical conditions
   find        find array indices of logical values
   isnan       detect NaNs
   finite      detect infinities
   isempty     detect empty matrices
   isstr       detect string variables
   strcmp      compare string variables


Control Flow

   if          conditionally execute statements
   elseif      used with if
   else        used with if
   end         terminate bif, for, while
   for         repeat statements a number of times
   while       do while
   break       break out of for and while loops
   return      return from functions
   pause       pause until key pressed


Programming and M-files

   input       get numbers from keyboard
   keyboard    call keyboard as M-file
   error       display error message
   function    define function
   eval        interpret text in variables
   feval       evaluate function given by string
   echo        enable command echoing
   exist       check if variables exist
   casesen     set case sensitivity
   global      define global variables
   startup     startup M-file
   getenv      get environment string
   menu        select item from menu
   etime       elapsed time
   tic,toc

Text and Strings

   abs         convert string to ASCII values
   eval        evaluate text macro
   num2str     convert number to string
   int2str     convert integer to string
   setstr      set flag indicating matrix is a string
   sprintf     convert number to string
   isstr       detect string variables
   strcomp     compare string variables
   hex2num     convert hex string to number


Command Window

   clc         clear command screen
   home        move cursor home
   format      set output display format
   disp        display matrix or text
   fprintf     print formatted number
   echo        enable command echoing


Graph Paper

   plot        linear X-Y plot
   plot3
   loglog      loglog X-Y plot
   semilogx    semi-log X-Y plot
   semilogy    semi-log X-Y plot
   polar       polar plot
   mesh        3-dimensional mesh surface
   surf
   contour     contour plot   
   meshgrid     domain for mesh plots
   bar         bar charts
   stairs      stairstep graph
   errorbar    add error bars


Graph Annotation

   title       plot title
   xlabel      x-axis label
   ylabel      y-axis label
   grid        draw grid lines
   text        arbitrarily position text
   gtext       mouse-positioned text
   ginput      graphics input
   zoom

Graph Window Control

   axis        manual axis scaling
   hold        hold plot on screen
   shg         show graph window
   clf         clear figure
   subplot     split graph window


Graph Window Hardcopy

   print       send graph to printer or file, several formats


Elementary Math Functions

   abs         absolute value or complex magnitude
   angle       phase angle
   sqrt        square root
   real        real part
   imag        imaginary part
   conj        complex conjugate
   round       round to nearest integer
   fix         round toward zero
   floor       round toward -infinity
   ceil        round toward infinity
   sign        signum function
   rem         remainder
   exp         exponential base e
   log         natural logarithm
   log10       log base 10


Trigonometric Functions

   sin         sine
   cos         cosine
   tan         tangent
   asin        arcsine
   acos        arccosine
   atan        arctangent
   atan2       four quadrant arctangent
   sinh        hyperbolic sine
   cosh        hyperbolic cosine
   tanh        hyperbolic tangent
   asinh       hyperbolic arcsine
   acosh       hyperbolic arccosine
   atanh       hyperbolic arctangent


Special Functions

   bessel      bessel function
   gamma       gamma function
   rat         rational approximation
   erf         error function
   inverf      inverse error function
   ellipk      complete elliptic integral of first kind
   ellipj      Jacobian elliptic integral


Decompositions and Factorizations

   balance     balanced form
   backsub     backsubstitution
   cdf2rdf     convert complex-diagonal to real-diagonal
   chol        Cholesky factorization
   eig         eigenvalues and eigenvectors
   hess        Hessenberg form
   inv         inverse
   lu          factors from Gaussian elimination
   nnls        nonnegative least squares
   null        null space
   orth        orthogonalization
   pinv        pseudoinverse
   qr          orthogonal-triangular decomposition
   qz          QZ algorithm
   rref        reduced row echelon form
   schur       Schur decomposition
   svd         singular value decomposition


Matrix Conditioning

   cond        condition number in 2-norm
   norm        1-norm,2-norm,F-norm, infinity-norm
   rank        rank
   rcond       condition estimate (reciprocal)


Elementary Matrix Functions

   expm        matrix exponential
   logm        matrix logarithm
   sqrtm       matrix square root
   funm        arbitrary matrix function
   poly        characteristic polynomial
   det         determinant
   trace       trace
   kron        Kronecker tensor product


Polynomials

   poly        characteristic polynomial
   roots       polynomial roots---companion matrix method
   roots1      polynomial roots---Laguerre's method
   polyval     polynomial evaluation
   polyvalm    matrix polynomial evaluation
   conv        multiplication
   deconv      division
   residue     partial-fraction expansion
   polyfit     polynomial curve fitting


Column-wise Data Analysis

   max         maximum value
   min         minimum value
   mean        mean value
   median      median value
   std         standard deviation
   sort        sorting
   sum         sum of elements
   prod        product of elements
   cumsum      cumulative sum of elements
   cumprod     cumulative product of elements
   diff        approximate derivatives
   hist        histograms
   corrcoef    correlation coefficients
   cov         covariance matrix
   cplxpair    reorder into complex pairs


Signal Processing

   abs         complex magnitude
   angle       phase angle
   conv        convolution
   corrcoef    correlation coefficients
   cov         covariance
   deconv      deconvolution
   fft         radix-2 fast Fourier transform
   fft2        two-dimensional FFT
   ifft        inverse fast Fourier transform
   ifft2       inverse 2-D FFT
   fftshift    FFT rearrangement

Numerical Integration

   quad        numerical function integration
   quad8       numerical function integration


Differential Equation Solution

   ode23       2nd/3rd order Runge-Kutta method
   ode45       4th/5th order Runge-Kutta-Fehlberg method


Nonlinear Equations and Optimization

   fmin        minimum of a function of one variable
   fmins       minimum of a multivariable function
   fsolve      solution of a system of nonlinear equations
               (zeros of a multivariable function)
   fzero       zero of a function of one variable


Interpolation

   polyfit
   spline      cubic spline
   table1      1-D table look-up
   table2      2-D table look-up