Matlab Fundamentals: Matrices
To fully understand how Matlab processes lists, we must discuss a bit
about linear algebra.
- When we define a list using a command such as t=1:3,
Matlab creates a row vector containing 3 elements.
- A row vectors can be turned into a column vector using the transpose
(') operator. Using the definition of t above, note what
happens for the command t' and t''
- The multiplication, division and exponential operators (*, /,
^) operating on two vectors will do matrix multiplications, not multiplying
the elements together.
- Given a list x=0:2:10; then x.*x or
x.^2 will give a list with the squares of the even integers
[0 4 16 36 64 100] because it is doing list
or array multiplication
- The command x*x will produce an error (since you can't
do matrix multiplication of two row vectors together).
- The command x*x' be will give the value of 220
(0+4+16+36+64+100=220) since the transpose operator (') means
that we have a row times column matrix (resulting in a scalar).
- The command x'*x will result in a 6 by 6 matrix
- We can extract and modify elements of a list
- Selecting an element of a list, use x(3)
- We can set an element using x(3)=100;
- To select a range of a lixt, use x(3:5) or x(:3)
or x(5:)
Two Dimensional Matrices and Three Dimensional Functions
- A 3x3 matrix can be initialized using . y = zeros(3)
- Using explicit references, e.g. A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
- Elements in each row are separated by spaces or commas
- Each row is separated by a semicolon or by pressing the return key
- Array operations (+ - .* ./ .^) operate on each element
of a matrix, For example, try A.^2 or A.*A
- Matrix operations are (+ - * / ^), For example, try
A^2 or A*A
- We can extend two 1-D vectors to a 2-D matrix (which we can use for
calculations) use meshgrid
- For example, we can make a multiplication table using array multiplication
- x = 1:5
- y = 0:3
- [X Y] = meshgrid(x,y)
- B = X .* Y
- Plot using mesh, surf, contour
- Calculate and Plot sinc(R)=sin(R)/R using (MAKE SURE YOU
USE .^ and ./)
- x = -16:1.1:16;
- [X Y] = meshgrid(x,x);
- R = sqrt(X.^2 + Y.^2);
- SincR = sin(R)./R;
- surf(X,Y,SincR)
- colorbar
- You can select subranges of matrices, A(3,3) or
A(1:2,1:2) or A(1:2,:) or A(:,2:3)
Electronic Copy: http://physics.gac.edu/~huber/matlab/mtlabmat.htm
Revised: 28-JAN-97 by Tom
Huber, Physics Department, Gustavus
Adolphus College.