2 Matlab
2 Matlab
This example shows basic techniques and functions for working with matrices in the MATLAB® language.
First, let's create a simple vector with 9 elements called a.
a = [1 2 3 4 6 4 3 4 5]
a =
1 2 3 4 6 4 3 4 5
Now let's add 2 to each element of our vector, a, and store the result in a new vector.
Notice how MATLAB requires no special handling of vector or matrix math.
b = a + 2
b =
3 4 5 6 8 6 5 6 7
Creating graphs in MATLAB is as easy as one command. Let's plot the result of our vector addition with grid
lines.
plot(b)
grid on
MATLAB can make other graph types as well, with axis labels.
bar(b)
xlabel('Sample #')
ylabel('Pounds')
MATLAB can use symbols in plots as well. Here is an example using stars to mark the points. MATLAB offers a
variety of other symbols and line types.
plot(b,'*')
axis([0 10 0 10])
One area in which MATLAB excels is matrix computation.
Creating a matrix is as easy as making a vector, using semicolons (;) to separate the rows of a matrix.
A = [1 2 0; 2 5 -1; 4 10 -1]
A =
1 2 0
2 5 -1
4 10 -1
1 2 4
2 5 10
0 -1 -1
Instead of doing a matrix multiply, we can multiply the corresponding elements of two matrices or vectors using
the .* operator.
C = A .* B
C =
1 4 0
4 25 -10
0 -10 1
Let's use the matrix A to solve the equation, A*x = b. We do this by using the \ (backslash) operator.
b = [1;3;5]
x = A\b
b =
1
3
5
x =
1
0
-1
r = A*x - b
r =
0
0
0
MATLAB has functions for nearly every type of common matrix calculation.
There are functions to obtain eigenvalues ...
eig(A)
ans =
3.7321
0.2679
1.0000
The "poly" function generates a vector containing the coefficients of the characteristic polynomial.
The characteristic polynomial of a matrix A is
p = round(poly(A))
p =
1 -5 5 -1
roots(p)
ans =
3.7321
1.0000
0.2679
whos
it is a command to find all the variables used
previously
sqrt(-1)
find the squreroot of the value