Sei sulla pagina 1di 11

1.

Tutorials on MATLAB MATRICES AND VECTORS


1.1 Dense matrices and vectors
1.2 Sparse matrices and vectors
1.3 Range operators
1.4 Grid operators
1.5 Size and shape operators
1.6 Special matrices
Matlab "thinks" in vector's and matrices, and it is most efficient if Matlab users treat every
variable as a vector or a matrix. I will followup on this latter. We will start by defining some
vectors and some matrices.
To practice these commands, either cut and paste or type something similar in you Matlab
window.

1.1 Define a dense matrix or vector

Define a matrix A -- use [] to signify the start and end. Use ; to signify the row breaks
>> A = [ 1 2; 3 4]
A =
1
3

2
4

Define a matrix A silently -- note the ; at the end of the line


>> A = [ 1 2; 3 4];

Define a row vector b


>> b = [1 2 3 4]
b =
1

Transpose it to a column vector -- use '

>> b = [1 2 3 4]'
b =
1
2
3
4

Enter it as a column vector


>> b = [1; 2; 3; 4]
b =
1
2
3
4

Change an element
>> b(1) = 4
b =
4
2
3
4

The current variables are;


>> whos
Name
A
b

Size

Bytes

2x2
4x1

32
32

Class
double array
double array

Grand total is 8 elements using 64 bytes

1.2 Define a sparse matrix or vector


A sparse matrix or vector usually has many zero entries

Convert from a dense matrix


>> A = sparse(A)

A =
(1,1)
(2,1)
(1,2)
(2,2)

1
3
2
4

Enter it directly
>> A(1,1) = 2
A =
(1,1)
(2,1)
(1,2)
(2,2)

2
3
2
4

1.3 Range operator ":"


The range operator allows one to set up a vector of equally spaced entries.

Defining vectors with the range operator


>> x = 1:4
x =
1

>> x = 1:2:6
x =
1

Accessing data from arrays with the range operator


>> A = [ 1 2; 3 4];
>> A(1,:)
ans =
1

>> A(:,1)
ans =

1
3
>> A = rand(4), x = 2:3
A =
0.9501
0.2311
0.6068
0.4860

0.8913
0.7621
0.4565
0.0185

0.8214
0.4447
0.6154
0.7919

0.9218
0.7382
0.1763
0.4057

x =
2

>> A(x,x)
ans =
0.7621
0.4565

0.4447
0.6154

1.4 Grid definition operators

Creating meshes of two dimensional coordinates


>> [x,y] = meshgrid(1:2,1:3)
x =
1
1
1

2
2
2

1
2
3

1
2
3

y =

1.5 Size and shape operators


These operators access basic array information

Find the length of a vector

>> b = [1 2 3 4]
>> length(b)
ans =
4

Find the size of a matrix


>> A = [ 1 2; 3 4];
>> size(A)
ans =
2

Reshape a matrix
>> A = [ 1 2; 3 4];
>> reshape(A,4,1)
ans =
1
3
2
4

Find the number of dimensions of a matrix


>> A = [ 1 2; 3 4];
>> ndims(A)
ans =
2

1.6 Special matrices


If you want a square matrix, these routines require only one size argument. If you want a
rectangular matrix, you must supply the dimensions.

A matrix of all zeros


>> A = zeros(4,2)
A =
0

0
0
0

0
0
0

A matrix of all ones


>> A = ones(4)
A =
1
1
1
1

1
1
1
1

1
1
1
1

1
1
1
1

A matrix of uniformly distribed random numbers on (0,1)


>> A = rand(4)
A =
0.2190
0.0470
0.6789
0.6793

0.9347
0.3835
0.5194
0.8310

0.0346
0.0535
0.5297
0.6711

An identity matrix
>> A = eye(4)
A =
1
0
0
0

0
1
0
0

0
0
1
0

0
0
0
1

0.0077
0.3834
0.0668
0.4175

2. Programming hints
2.1 Some basics
2.2 m-files
2.3 Good practices
At the user's level Matlab is an interpreted language that accesses compiled software.
This has disadvantages and advantages.
The advantage of this is that Matlab code is easy to debug. When I write Matlab code,
I have an editor open in one window and I run Matlab in another window. Then I
write a few lines of code, and I cut that code out of the edit window and paste it into
the Matlab window to test it. This is very useful and fast.
The disadvantage is that the interpreter is extremely slow. Therefore, to make Matlab a
useful tool for numerical simulation, it is critical that you try to write code that utilizes
the compiled (and consequently, fast) subroutines more than it utilizes the interpreter.
I talk about this more below.

2.1 Some basics

Looping is done with the for command. The syntax is


>> for i = first : increment : last
commands
end

The default increment is one. For example,


>> for i = 1:n
sum = sum + x(i)*y(i);
end

calculate the dot product of x and y.


Conditional statements are evaluated with the if, while and switch commands. The
syntax for if is

>> if

expression
commands

elseif expression
commands
else
commands
end

2.2 m-files

Matlab allows the user to write programs, save them on the disk, and then to execute
them. These programs are called m-files. By convention, they are named foo.m. To see
an example of an m-file type
>> help function

This shows a function for computing the mean and standard deviation of a vector x.
The format for a matlab m-file is shown in the stat function. Copy that format for your
m-files. Another version of a m-file was shown in the ODE section of this web-page,
>> type lotka

This file specifies the right hand side of an ordinary differential equation that models a
population of predators and their prey.
2.3 Good practices

My standard of good may be a bit different from what other standards of good are, but
by "good Matlab code", I mean, code that runs fast and is understandable to people
beyond its author.
Its relatively easy to write code that others can understand. Add comments to your
code to explain what you are doing. If a segment of code needs more than a few of
lines of comments, break it up into smaller parts and comment those, or put it into an
m-file.

Code that runs fast is code that does not invoke the Matlab interpreter
disproprotionately often compared to the Matlab software. Obviously, this is more
important for large and difficult problems, but its a good thing to keep in mind at all
times.

To demostrate the Matlab interpreter's slow speed, we will consider the problem of
multiplying two 100 by 100 matrices. In the following code segment, I define three
matrices, A, B and C, and multiply them together by computing the inner product of
the rows of A with the columns of B. This code is similar to code you would write if
you were using C or FORTRAN.
>>
>>
>>
>>
>>

% Matrix multiplication example using full looping

n = 100; A = rand(n); B=rand(n); C=zeros(n);


t = cputime;
for i=1:n,
for j=1:n,
for k=1:n
C(i,j) = C(i,j) + (A(i,k)*B(k,j));
end
end
end
>> t = cputime-t
t = 97.9600

Notice that the time required for this segment of code. There are nine permutations of
this scheme, and all have similar timings.
We now consider using the colon range operator to compute the product of A and B by
looping over all of the elements of the resulting matrix C. Notice that what is being
computed for a given i and j is the dot product of the i^(th) row of A with the j^(th)
column of B.
>> % Matrix multiplication example using inner products
>>
>> t = cputime;
>> for i=1:n,
for j=1:n
C(i,j) = A(i,:)*B(:,j);
end
end
>> t = cputime-t
t =
2.6600

Again the time this segment of code took to complete the calculation. By eliminating
the inner loop, we have decreased the effort required to compute C by a factor of 37
times!
Finally, we make use of the * operator, i.e. we use the full compiled code to compute
C.
>> t = cputime;

C = A*B;

t = cputime-t

t =
0.0400

This segment of code took 0.04 seconds, a savings of 2450 times over the fully looped
calculation and 66 times over the inner product calculation.
You would not want to program matrix multiplication if you are using Matlab, but this
example should serve as an illustration of the kind of code that you should avoid
writting if possible.
On the other hand, be careful that you don't get too carried away with this process.
The following code segments assign a vector to the sum the first j elements of another
vector, i.e.
y_j = x_1 + x_2 + ... + x_j
clear; n=2000; x = 1:n; x = x(:); y = zeros(n,1);
% case 1 -- no vectorization
t=cputime; for j=1:n, for k=1:j, y(j)=y(j)+x(k); end, end, cputime-t
% case 2 -- partial vectorization
t=cputime; for j=1:n, y(j)=sum(x(1:j)); end, cputime-t
% case 3 -- full vectorization
t=cputime; y = tril(ones(n))*x; cputime-t

The partially vectorized case is much faster than the case without any vectorization,
but the fully vectorized case takes more time than the partially vectorized case
because it computes too many multiplications that are equal to zero.
I'll close this section with a couple of suggestions for writing efficient Matlab code.

Your code is only as good as your algorithm. Find a good algorithm if you
can.
Avoid accessing arrays via their individual elements. Use vectors instead. For
example, use
>> n = 11; x = rand(n); y = rand(n)
>> z = x(1:2:n) + y(1:2:n)

instead of
>> for i=1:2:n z(i) = x(i) + y(i); end

The result is easier to read and faster.


Avoid nested looping. Looping is expensive because it accesses array elements.
Avoid too many conditional statements.

Potrebbero piacerti anche