Introduction to MATLAB
1.1 Numerical Calculations with MATLAB
You can use MATLAB as a powerful numerical calculator. While most calculators handle numbers only to a preset degree of accuracy, MATLAB works to whichever precision is necessary for any given calculation. In addition, unlike calculators, we can perform operations not only with individual numbers, but also with objects such as matrices.
Most classical numerical analysis topics are treated by MATLAB. It supports matrix algebra, statistics, interpolation, fit by least squares, numerical integration, minimization of functions, linear programming, numerical solutions of algebraic equations and differential equations and a long list of further techniques.
Here are some examples of numerical calculations with MATLAB (once the commands have been entered to the right of the input prompt “>>” simply hit Enter to obtain the result):
>> 4 + 3
ans =
7
>> 3 ^ 100
ans =
5. 1538e + 047
>> format long e;
>> 3 ^ 100
ans =
5.153775207320115e+047
>> (2 + 3i) ^ 10
ans =
-3 415250000000001e + 005 - 1. 456680000000001e + 005i
The command format long g will optimize the output of future calculations.
>> format long g
>> (2 + 3i) ^ 10
ans =
-341525 - 145668i
>> format short;
>> (2 + 3i) ^ 10
ans =
-3.4152e+005- 1.4567e+005i
>> Besselj(0,13.5)
ans =
0.2150
>> syms x
>> int(sin(x), 0, pi)
ans =
2
These themes will be treated more thoroughly later.
1.2 Symbolic Calculations with MATLAB
MATLAB handles symbolic mathematical computation perfectly, manipulating formulae and algebraic expressions easily and efficiently. You can expand, factor and simplify polynomials, rational functions and trigonometric expressions; you can find algebraic solutions of polynomial equations and systems of equations; you can evaluate derivatives and integrals symbolically and find solutions of differential equations; you can manipulate power series, find limits and explore many other facets of algebraic series.
To perform this task, MATLAB requires that all variables (or algebraic expressions) are previously declared as symbolic using the command syms.
Here are some examples of symbolic computations with MATLAB:
>> syms x
>> expand (((x + 1)*(x + 2)-(x + 2)^2)^3).
ans =
-x ^ 3-6 * x ^ 2-12 * x-8
>> syms x
>> factor(((x + 1)*(x + 2)-(x + 2)^2)^3)
ans =
-(x+2) ^ 3
>> syms x
>> int(x^2*sin(x)^2, x)
ans =
x ^ 2 * (-1/2 * cos(x) * sin(x) + 1/2 * x)-1/2 * x * cos(x) ^ 2 + 1/4 * cos(x) * sin(x) + 1/4 * 1/x-3 * x ^ 3
>> syms x
>> simplify(int(x^2*sin(x)^2, x))
ans =
-1/2 * x ^ 2 * cos(x) * sin(x) + 1/6 * x ^ 3-1/2 * x * cos(x) ^ 2 + 1/4 * cos(x) * sin(x) + 1/4 * x
>> syms x
>> pretty(simplify(int('x^2*sin(x)^2', 'x')))
2 3 2
-1/2 x cos(x) sin(x) + 1/6 x - 1/2 x cos(x) + 1/4 cos(x) sin(x) + 1/4 x
>> syms x
>> pretty(taylor(x^2*sin(x)^2,12))
4 6 8 10 12
x 1/3 x + 2/45 x - 1/315 x + 0 (x)
>> syms x a
>> solve('3*a*x-7*x^2 + x^3 = 0', x)
ans =
[ 0 ]
[7/2 + 1/2 *(49-12*a) ^(1/2)]
[7/2-1/2 *(49-12*a) ^(1/2) ]
>> syms x
>> solve('x^5+2*x+1','x')
ans =
[-.7018735688558619 -.8796971979298240 * i]
[-.7018735688558619 +.8796971979298240 * i]
[-.4863890359345430 ]
[ .9450680868231334 -.8545175144390459 * i]
[ .9450680868231334 +.8545175144390459 * i]
On the other hand, MATLAB can be used together with the Maple program libraries to work with symbolic mathematics, thus extending its field of action. In this way, MATLAB can be used to work on topics such as differential forms, Euclidean geometry, projective geometry, statistics, etc.
At the same time, we can extend MATLAB’s numerical calculation cababilities by using the Maple libraries (combinatorics, optimization, number theory, statistics, etc.)
1.3 MATLAB and Maple
Whenever it is necessary to use a Maple command or function from MATLAB, use the command maple followed by the corresponding Maple syntax. This functionality is only available if you have installed the symbolic computation Toolbox “Extended Symbolic Math Toolbox”. This is the tool one uses to work with linear algebra and mathematical analysis.
To use a Maple command from MATLAB, the syntax is as follows:
Let’s see some examples:
>> maple('limit((x^3-1)/(x-1),x=1)')
ans =
3
We could also have used the following syntax:
>> maple 'limit((x^3-1)/(x-1),x=1)'
ans =
3
>> maple('gcd', 10000, 5000)
ans =
5000
1.4 General Notation. The Command Window
Whenever a program is used, it is necessary to become familiar with the general characteristics of its notation. Like any program, the best way to learn MATLAB is to use it. Each example consists of the user input prompt “>>” followed by the command and the MATLAB response on the next line. See Figure 1-1.
Sometimes, depending on the type of command (user input) given to MATLAB in the Command Window, the response will begin with the expression ans =. See Figure 1-2.
It is important to pay attention to uppercase and lowercase characters, parentheses and square brackets, and the use of spaces and punctuation (in particular commas and semicolons).
Like the C programming language, MATLAB is case sensitive; for example, Sin(x) is different to sin(x). The names of all built-in functions begin with lowercase letters. Each bracket has its own meaning, as we will see later.
To indicate that two variables must be multiplied you put the symbol * between them, and there cannot be spaces in the names of commands, variables or functions. In other cases, spaces are ignored, but they can be included to make the input more readable.
Once a MATLAB command has been entered, simply press Enter. If at the end of the input we put a semicolon, the program runs the calculation and keeps it in memory (Workspace), but does not display the result on screen. The input prompt “>>” reappears to indicate that you can input a new entry.
>> 2 + 3;
>>
If the entry is too long and doesn’t fit on a single line of the MATLAB Command Window, just put three dots at the end of the line and press Enter to continue with the rest of the entry on the next line. Once the entry is complete, press Enter to run the command:
>> 1254 + 3456789 + 14267890 + 345217 +...
78965 + 125347 + 86500
ans =
18361962
>>
You can make multiple entries in the same command line by separating them with commas and pressing Enter at the end of the last entry. If you use a semicolon at the end of one of the entries of the line, its corresponding output is ignored. If the number of consecutive entries doesn’t fit on one line, three dots are used to continue on the next line, as described above:
>> 2+2, 5+3, 8+5
ans =
4
ans =
8
ans =
13
>> 2+2; 5+3, 8+5; 3*4
ans =
8
ans =
12
To enter a descriptive comment in a command line, just start it with the “%” symbol. When you run the input, MATLAB will ignore the comment and process the rest.
>> F = 125 + 2 %F represents units of force
F =
127
To simplify the process of entering a script to be evaluated by the MATLAB interpreter (via the command window prompt), you can use arrow keys. For example, if you press the up arrow once, you recover the last entry submitted in MATLAB. If you press the up arrow twice, you recover the penultimate entry submitted, and so on.
If you type a sequence of characters in the input area and then click the up arrow, you recover the last entry that begins with the specified string.
The commands entered during a MATLAB session are stored temporarily in the buffer (Workspace) until the end of the session, at which time you can permanently save the session to file or lose it.
Below is a summary of the keys that can be used in the MATLAB command line, and their functions:
Up Arrow (Ctrl-P) |
Retrieves the entry preceding the current one. |
Down Arrow (Ctrl-N) |
Retrieves the entry following the current one. |
Left Arrow (Ctrl-B) |
Moves the cursor one character to the left. |
Right Arrow (Ctrl-F) |
Moves the cursor one character to the right. |
CTRL-Left Arrow |
Moves the cursor one word to the left. |
CTRL-Right Arrow |
Moves the cursor one word to the right. |
Home (Ctrl-A) |
Moves the cursor to the beginning of the current line. |
End (Ctrl-E) |
Moves the cursor to the end of the current line. |
Escape |
Clears the command line. |
Delete (Ctrl-D) |
Erases the character indicated by the cursor. |
Backspace |
Deletes the character to the left of the cursor. |
CTRL-K |
Clears (kills) the entire current line. |
The command clc clears the command window, but does not delete the contents of the work area (the content currently in memory).
1.5 MATLAB and Programming
By properly combining all the features of MATLAB, one can build useful mathematical research programming code. Programs usually consist of a sequence of instructions in which various values are calculated. These sequences of commands are assigned names and can be reused in further calculations.
As in programming languages like C or Fortran, MATLAB supports loops, control flow and conditional statements. MATLAB can write procedural programs, i.e., it can define a sequence of standard steps to run. As in C or Pascal, one can repeat calculations using Do, For, or While loops. The language of MATLAB also includes conditional constructs such as If Then Else. MATLAB also supports different logical operators, such as And, Or, Not and Xor.
MATLAB supports procedural programming (with iterative processes, recursive functions, loops...), functional programming and object-oriented programming. Here are two simple examples of programs. The first generates the order n Hilbert matrix, and the second calculates the Fibonacci numbers less than 1000.
% Generates the order n Hilbert matrix
t = '1/(i+j-1)';
for i = 1:n
for j = 1:n
a(i,j) = eval(t);
end
end
% Calculates Fibonacci numbers
f = [1 1]; i = 1;
while f(i) + f(i-1) < 1000
f(i+2) = f(i) + f(i+1);
i = i+1
end
1.6 Translating C, FORTRAN and TEX expressions
MATLAB offers the possibility to translate math expressions to code in other programming languages such as Fortran or C. Additionally, it can also translate expressions to eqn and TeX form. To do this, one can use the following commands:
As examples, we translate the integral of 1 /(x4+1) to TeX, Fortan and C:
>> maple('latex(Int(1/(x^4+1),x))')
ans =
int !left ({x}^{4}+1 ight )^{-1}{dx}
>> maple('fortran(Int(1/(x^4+1),x))')
ans =
t0 = Int(1/(x**4+1),x)
>> maple('readlib(C)'); maple('C(Int(1/(x^4+1),x))')
ans =
t0 = Int(1/(pow(x,4.0)+1.0),x);