Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


Partial Differential Equations in MATLAB, Notas de estudo de Engenharia Elétrica

Partial Differential Equations: Analytical and Numerical Methods

Tipologia: Notas de estudo

2013

Compartilhado em 01/07/2013

eloy-medici-6
eloy-medici-6 🇧🇷

5

(1)

10 documentos

1 / 136

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
1
MATLAB Tutorial
to accompany
Partial Differential Equations: Analytical and Numerical
Methods, 2nd edition
by
Mark S. Gockenbach
(SIAM, 2010)
MATLAB Tutorial ....................................................................................................................................... 1
Introduction ................................................................................................................................................ 3
About this tutorial................................................................................................................................... 3
About MATLAB .................................................................................................................................... 3
MATLAB M-Book................................................................................................................................. 3
Getting help with MATLAB commands................................................................................................ 4
Getting started with MATLAB............................................................................................................... 4
Vectors and matrices in MATLAB......................................................................................................... 8
More about M-Books ............................................................................................................................. 9
Simple graphics in MATLAB ................................................................................................................ 9
Symbolic computation in MATLAB.................................................................................................... 15
Manipulating functions in MATLAB................................................................................................... 18
Saving your MATLAB session ............................................................................................................ 20
About the rest of this tutorial................................................................................................................ 20
Chapter 1: Classification of differential equations.................................................................................. 21
Chapter 2: Models in one dimension ........................................................................................................ 24
Section 2.1: Heat flow in a bar; Fourier's Law ......................................................................................... 24
Solving simple boundary value problems by integration ..................................................................... 25
The MATLAB solve command............................................................................................................ 26
Chapter 3: Essential linear algebra .......................................................................................................... 31
Section 3.1 Linear systems as linear operator equations .......................................................................... 31
Section 3.2: Existence and uniqueness of solutions to Ax=b ................................................................... 32
Section 3.3: Basis and dimension............................................................................................................. 35
Symbolic linear algebra........................................................................................................................ 37
Programming in MATLAB, part I........................................................................................................ 38
Defining a MATLAB function in an M-file. ........................................................................................38
Optional inputs with default values ...................................................................................................... 43
Comments in M-files............................................................................................................................ 44
M-files as scripts................................................................................................................................... 44
Section 3.4: Orthogonal bases and projection .......................................................................................... 46
Working with the L2 inner product ....................................................................................................... 46
Section 3.5: Eigenvalues and eigenvectors of a symmetric matrix........................................................... 53
Numerical eigenvalues and eigenvectors.............................................................................................. 53
Symbolic eigenvalues and eigenvectors............................................................................................... 53
Review: Functions in MATLAB .......................................................................................................... 56
Chapter 4: Essential ordinary differential equations.............................................................................. 59
Section 4.2: Solutions to some simple ODEs........................................................................................... 59
Second-order linear homogeneous ODEs with constant coefficients................................................... 60
A special inhomogeneous second-order linear ODE............................................................................ 61
First-order linear ODEs ........................................................................................................................ 62
Section 4.3: Linear systems with constant coefficients ............................................................................ 64
Inhomogeneous systems and variation of parameters .......................................................................... 66
Programming in MATLAB, Part II ...................................................................................................... 68
Conditional execution........................................................................................................................... 69
Passing one function into another......................................................................................................... 70
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe Partial Differential Equations in MATLAB e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!

MATLAB Tutorial

to accompany

nd

edition

by Mark S. Gockenbach

Since the M-Book facility is available only under Microsoft Windows, I will not emphasize it in this tutorial. However, Windows users should take advantage of it. The most important thing to understand about a M-Book is that it is interactive---at any time you can execute a MATLAB command and see what it does. This makes a MATLAB M-Book a powerful learning environment: when you read an explanation of a MATLAB feature, you can immediately try it out.

Getting help with MATLAB commands

Documentation about MATLAB and MATLAB commands is available from within the program itself. If you know the name of the command and need more information about how it works, you can just type " help " at the MATLAB prompt. In the same way, you can get information about a group of commands with common uses by typing " help ". I will show examples of using the command-line help feature below.

The MATLAB desktop contains a help browser covering both reference and tutorial material. To access the browser, click on the Help menu and choose MATLAB Help. You can then choose " Getting Started " from the table of contents for a tutorial introduction to MATLAB, or use the index to find specific information.

Getting started with MATLAB

As mentioned above, MATLAB has many capabilities, such as the fact that one can write programs made up of MATLAB commands. The simplest way to use MATLAB, though, is as an interactive computing environment (essentially, a very fancy graphing calculator). You enter a command and MATLAB executes it and returns the result. Here is an example:

clear 2+ ans = 4

You can assign values to variables for later use:

x= x = 2

The variable x can now be used in future calculations:

x^ ans = 4

At any time, you can list the variables that are defined with the who command:

who

Your variables are:

ans x

At the current time, there are 2 variables defined. One is x , which I explicitly defined above. The other is ans (short for "answer"), which automatically holds the most recent result that was not assigned to a variable (you may have noticed how ans appeared after the first command above). You can always check the value of a variable simply by typing it:

x x = 2

ans ans = 4

If you enter a variable that has not been defined, MATLAB prints an error message:

y ??? Undefined function or variable 'y'.

To clear a variable from the workspace, use the clear command:

who

Your variables are:

ans x

clear x

who

Your variables are:

ans

To clear of the variables from the workspace, just use clear by itself:

clear who

MATLAB knows the elementary mathematical functions: trigonometric functions, exponentials, logarithms, square root, and so forth. Here are some examples:

sqrt(2) ans =

sin(pi/3) ans =

exp(1) ans =

log(ans)

log1p - Compute log(1+x) accurately. log10 - Common (base 10) logarithm. log2 - Base 2 logarithm and dissect floating point number. pow2 - Base 2 power and scale floating point number. realpow - Power that will error out on complex result. reallog - Natural logarithm of real number. realsqrt - Square root of number greater than or equal to zero. sqrt - Square root. nthroot - Real n-th root of real numbers. nextpow2 - Next higher power of 2.

Complex. abs - Absolute value. angle - Phase angle. complex - Construct complex data from real and imaginary parts. conj - Complex conjugate. imag - Complex imaginary part. real - Complex real part. unwrap - Unwrap phase angle. isreal - True for real array. cplxpair - Sort numbers into complex conjugate pairs.

Rounding and remainder. fix - Round towards zero. floor - Round towards minus infinity. ceil - Round towards plus infinity. round - Round towards nearest integer. mod - Modulus (signed remainder after division). rem - Remainder after division. sign - Signum.

For more information about any of these elementary functions, type " help <function_name>". For a list of help topics like "elfun", just type " help ". There are other commands that form part of the help system; to see them, type " help help ".

MATLAB does floating point arithmetic using the IEEE standard, which means that numbers have about 16 decimal digits of precision (the actual representation is in binary, so the precision is not exactly 16 digits). However, MATLAB only displays 5 digits by default. To change the display, use the format command. For example, " format long " changes the display to 15 digits:

format long

pi ans =

Other options for the format command are " format short e " (scientific notation with 5 digits) and " format long e " (scientific notation with 15 digits).

In addition to pi , other predefined variables in MATLAB include i and j , both of which represent the imaginary unit: i=j=sqrt(-1).

clear i^ ans =

j^ ans =

Although it is usual, in mathematical notation, to use i and j as arbitrary indices, this can sometimes lead to errors in MATLAB because these symbols are predefined. For this reason, I will use ii and jj as my standard indices when needed.

Vectors and matrices in MATLAB

The default type for any variable or quantity in MATLAB is a matrix---a two-dimensional array. Scalars and vectors are regarded as special cases of matrices. A scalar is a 1 by 1matrix, while a vector is an n by 1 or 1 by n matrix. A matrix is entered by rows, with entries in a row separated by spaces or commas, and the rows separated by semicolons. The entire matrix is enclosed in square brackets. For example, I can enter a 3 by 2 matrix as follows:

A=[1 2;3 4;5 6]

A =

Here is how I would enter a 2 by 1 (column) vector:

x=[1;-1] x = 1

A scalar, as we have seen above, requires no brackets:

a= a = 4

A variation of the who command, called whos , gives more information about the defined variables:

whos Name Size Bytes Class Attributes

A 3x2 48 double a 1x1 8 double ans 1x1 8 double x 2x1 16 double

The column labeled "size" gives the size of each array; you should notice that, as I mentioned above, a scalar is regarded as a 1 by 1 matrix (see the entry for a , for example).

MATLAB can perform the usual matrix arithmetic. Here is a matrix-vector product:

Ax* ans =

y=[1,0,1,0,1] y = 1 0 1 0 1

plot(x,y)

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

0

1

Two features of MATLAB make it easy to generate graphs. First of all, the command linspace creates a vector with linearly spaced components---essentially, a regular grid on an interval. (Mathematically, linspace creates a finite arithmetic sequence.) To be specific, linspace(a,b,n) creates the (row) vector whose components are a , a + h , a+ 2 h ,…, a +( n -1) h , where h =1/( n -1).

x=linspace(0,1,6) x = 0 0.2000 0.4000 0.6000 0.8000 1.

The second feature that makes it easy to create graphs is the fact that all standard functions in MATLAB, such as sine, cosine, exp, and so forth, are vectorized. A vectorized function f , when applied to a vector x , returns a vector y (of the same size as x ) with i th component equal to f ( xi ). Here is an example:

y=sin(pix)* y = 0 0.5878 0.9511 0.9511 0.5878 0.

I can now plot the function:

plot(x,y)

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

0

1

Of course, this is not a very good plot of sin( x ), since the grid is too coarse. Below I create a finer grid and thereby obtain a better graph of the function. Often when I create a new vector or matrix, I do not want MATLAB to display it on the screen. (The following example is a case in point: I do not need to see the 41 components of vector x or vector y .) When a MATLAB command is followed by a semicolon, MATLAB will not display the output.

x=linspace(0,1,41); y=sin(pix); plot(x,y)*

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

0

1

If I prefer, I can just graph the points themselves, or connect them with dashed line segments. Here are examples:

 - Methods, Partial Differential Equations: Analytical and Numerical 
  • MATLAB Tutorial (SIAM, 2010)
    • Introduction
      • About this tutorial...................................................................................................................................
      • About MATLAB
      • MATLAB M-Book.................................................................................................................................
      • Getting help with MATLAB commands
      • Getting started with MATLAB...............................................................................................................
      • Vectors and matrices in MATLAB.........................................................................................................
      • More about M-Books
      • Simple graphics in MATLAB
      • Symbolic computation in MATLAB
      • Manipulating functions in MATLAB...................................................................................................
      • Saving your MATLAB session
      • About the rest of this tutorial................................................................................................................
  • Chapter 1: Classification of differential equations
  • Chapter 2: Models in one dimension
    • Section 2.1: Heat flow in a bar; Fourier's Law
      • Solving simple boundary value problems by integration
      • The MATLAB solve command
  • Chapter 3: Essential linear algebra
    • Section 3.1 Linear systems as linear operator equations
    • Section 3.2: Existence and uniqueness of solutions to Ax=b
    • Section 3.3: Basis and dimension
      • Symbolic linear algebra
      • Programming in MATLAB, part I........................................................................................................
      • Defining a MATLAB function in an M-file.
      • Optional inputs with default values
      • Comments in M-files............................................................................................................................
      • M-files as scripts...................................................................................................................................
    • Section 3.4: Orthogonal bases and projection
      • Working with the L^2 inner product
    • Section 3.5: Eigenvalues and eigenvectors of a symmetric matrix...........................................................
      • Numerical eigenvalues and eigenvectors..............................................................................................
      • Symbolic eigenvalues and eigenvectors
      • Review: Functions in MATLAB
  • Chapter 4: Essential ordinary differential equations..............................................................................
    • Section 4.2: Solutions to some simple ODEs
      • Second-order linear homogeneous ODEs with constant coefficients
      • A special inhomogeneous second-order linear ODE
      • First-order linear ODEs
    • Section 4.3: Linear systems with constant coefficients
      • Inhomogeneous systems and variation of parameters
      • Programming in MATLAB, Part II
      • Conditional execution...........................................................................................................................
      • Passing one function into another.........................................................................................................
    • Section 4.4: Numerical methods for initial value problems
      • Programming in MATLAB, part III
      • Efficient MATLAB programming........................................................................................................
      • More about graphics in MATLAB
  • Chapter 5: Boundary value problems in statics.......................................................................................
    • Section 5.2: Introduction to the spectral method; eigenfunctions............................................................
    • Section 5.5: The Galerkin method
      • Computing the stiffness matrix and load vector in loops
    • Section 5.6: Piecewise polynomials and the finite element method
      • Computing the load vector
      • Computing the stiffness matrix.............................................................................................................
      • The nonconstant coefficient case..........................................................................................................
      • Creating a piecewise linear function from the nodal values
      • More about sparse matrices
  • Chapter 6: Heat flow and diffusion.........................................................................................................
    • Section 6.1: Fourier series methods for the heat equation
    • Section 6.4: Finite element methods for the heat equation.....................................................................
  • Chapter 8: First-Order PDEs and the Method of Characteristics.......................................................
    • Section 8.1: The simplest PDE and the method of characteristics..........................................................
      • Two-dimensional graphics in MATLAB............................................................................................
    • Section 8.2: First-order quasi-linear PDEs
  • Chapter 11: Problems in multiple spatial dimensions...........................................................................
    • Section 11.2: Fourier series on a rectangular domain.............................................................................
    • Section 8.3: Fourier series on a disk.......................................................................................................
      • Graphics on the disk
  • Chapter 12: More about Fourier series
    • Section 12.1: The complex Fourier series
    • Section 9.2: Fourier series and the FFT..................................................................................................
  • Chapter 13: More about finite element methods
    • Section 13.1 Implementation of finite element methods
      • Creating a mesh
      • Computing the stiffness matrix and the load vector
      • Testing the code..................................................................................................................................
      • Using the code
      • -5 -4 -3 -2 -1
  • -0.
  • -0.
  • -0.
  • -0.
  • -0.
      • -5 -4 -3 -2 -1 plot(x,y,'.')
  • -0.
  • -0.
  • -0.
  • -0.
  • -0.

-5 -4 -3 -2 -1 0 1 2 3 4 5

-0.

-0.

-0.

-0.

-0.

0

plot(x,y,'--')

-5 -4 -3 -2 -1 0 1 2 3 4 5

-0.

-0.

-0.

-0.

-0.

0

The string following the vectors x and y in the plot command ('.', 'o', and '—' in the above examples) specifies the line type. it is also possible to specify the color of the graph. For more details, see " help plot ".

It is not much harder to plot two curves on the same graph. For example, I plot y =x 2 and y =x 3 together:

x=linspace(-1,1,101); plot(x,x.^2,x,x.^3)

syms a b

I can now form symbolic expressions involving these variables:

2ab** ans = 2ab

Notice how the result is symbolic, not numeric as it would be if the variables were floating point variables. Also, the above calculation does not result in an error, even though a and b do not have values.

Another way to create a symbolic variable is to assign a symbolic value to a new symbol. Since numbers are, by default, floating point, it is necessary to use the sym function to tell MATLAB that a number is symbolic:

c=sym(2) c = 2

whos Name Size Bytes Class Attributes

A 3x2 48 double B 2x4 64 double a 1x1 60 sym ans 1x1 60 sym b 1x1 60 sym c 1x1 60 sym x 1x101 808 double y 1x41 328 double z 3x1 24 double

I can do symbolic computations:

a=sqrt(c) a = 2^(1/2)

You should notice the difference between the above result and the following:

a=sqrt(2) a =

whos Name Size Bytes Class Attributes

A 3x2 48 double B 2x4 64 double a 1x1 8 double ans 1x1 60 sym b 1x1 60 sym c 1x1 60 sym x 1x101 808 double y 1x41 328 double

z 3x1 24 double

Even though a was declared to be a symbolic variable, once I assign a floating point value to it, it becomes numeric. This example also emphasizes that sym must be used with literal constants if they are to interpreted as symbolic and not numeric:

a=sqrt(sym(2)) a = 2^(1/2)

As a further elementary example, consider the following two commands:

sin(sym(pi)) ans = 0

sin(pi) ans = 1.2246e-

In the first case, since π is symbolic, MATLAB notices that the result is exactly zero; in the second, both π and the result are represented in floating point, so the result is not exactly zero (the error is just roundoff error).

Using symbolic variables, I can perform algebraic manipulations.

syms x p=(x-1)(x-2)(x-3)** p = (x - 1)(x - 2)(x - 3)

expand(p) ans = x^3 - 6x^2 + 11x - 6

factor(ans) ans = (x - 3)(x - 1)(x - 2)

Integers can also be factored, though the form of the result is depends on whether the input is numeric or symbolic:

factor(144) ans = 2 2 2 2 3 3 factor(sym(144)) ans = 2^4*3^

For a numeric (integer) input, the result is a list of the factors, repeated according to multiplicity. For a symbolic input, the output is a symbolic expression.

An important command for working with symbolic expressions is simplify , which tries to reduce an expression to a simpler one equal to the original. Here is an example:

clear

plot(y,z)

-5 -4 -3 -2 -1 0 1 2 3 4 5

-0.

-0.

-0.

-0.

-0.

0

One of the most powerful features of symbolic computation in MATLAB is that certain calculus operations, notably integration and differentiation, can be performed symbolically. These capabilities will be explained later in the tutorial.

Above I showed how to evaluate a function defined by a symbolic expression. It is also possible to explicitly define a function at the command line. Here is an example:

f=@(x)x^ f = @(x)x^

The function f can be evaluated in the expected fashion, and the input can be either floating point or symbolic:

f(1) ans = 1 f(sqrt(pi)) ans =

f(sqrt(sym(pi))) ans = pi

The @ operator can also be used to create a function of several variables:

g=@(x,y)x^2y* g = @(x,y)x^2*y g(1,2) ans =

g(pi,14) ans =

A function defined by the @ operator is not automatically vectorized:

x=linspace(0,1,11)'; y=linspace(0,1,11)'; g(x,y) ??? Error using ==> mpower Inputs must be a scalar and a square matrix. To compute elementwise POWER, use POWER (.^) instead.

Error in ==> @(x,y)x^2y*

The function can be vectorized when it is defined:

g=@(x,y)x.^2.y* g = @(x,y)x.^2.*y g(x,y) ans = 0

There is a third way to define a function in MATLAB, namely, to write a program that evaluates the function. I will defer an explanation of this technique until Chapter 3, where I first discuss programming in MATLAB.

Saving your MATLAB session

When using MATLAB, you will frequently wish to end your session and return to it later. Using the save command, you can save all of the variables in the MATLAB workspace to a file. The variables are stored efficiently in a binary format to a file with a ".mat" extension. The next time you start MATLAB, you can load the data using the load command. See "help save" and "help load" for details.

About the rest of this tutorial

The remainder of this tutorial is organized in parallel with my textbook. Each section in the tutorial introduces any new MATLAB commands that would be useful in addressing the material in the corresponding section of the textbook. As I mentioned above, some sections of the textbook have no counterpart in the tutorial, since all of the necessary MATLAB commands have already been explained. For this reason, the tutorial is intended to be read from beginning to end, in conjunction with the textbook.