




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Prepare-se para as provas
Estude fácil! Tem muito documento disponível na Docsity
Prepare-se para as provas com trabalhos de outros alunos como você, aqui na Docsity
Encontra documentos específicos para os exames da tua universidade
Prepare-se com as videoaulas e exercícios resolvidos criados a partir da grade da sua Universidade
Responda perguntas de provas passadas e avalie sua preparação.
Ganhe pontos para baixar
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Partial Differential Equations: Analytical and Numerical Methods
Tipologia: Notas de estudo
1 / 136
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































to accompany
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
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:
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 -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.