next up previous contents
Next: 3.2 Manipulating matrices and Up: 3. More on matrices Previous: 3. More on matrices   Contents

3.1 Creating matrices and vectors
and indexing elements

Few problems in computational physics can be solved without using matrices and vectors. In this chapter we'll cover in some additional detail how to handle arrays as matrices and vectors. Define an array (a vector) named $a$ containing all of the integers from $-5$ to 10 in reverse order.(Don't do it explicitly--use the colon notation.) If you've already forgotten how, go back and reread the end of Section 1.4.1. Define another array named $b$ that contains the square roots of each element in the first array. We can use the ``subscript notation'' to access individual elements of an array. For example, a(6) gives 5 while b(6) gives $\sqrt(5)=2.2361$. To access a block of elements, we can use the ``colon notation.'' To access the last four elements of $a$, type a(13:16) or a(13:end). Try it on $b$ too. Type the following, b(end:-1:11). How does this work? How about this: a(2:2:7)? If you can't figure out what is going, ask the TA or instructor. There are several ways to define the elements of an array. We can specify each one explicitly, use the colon operator, or use the commands linspace or logspace. Here is an example or two of each. Pay attention as you do each one and make sure you understand how it works. These examples are best done one-by-one at the command line rather than in an M-file.
% Constructing arrays
close all; clear all;

% Simple assignment (explicit construction)
a = [3 2 1 7 9]
b = [2 3.0 sqrt(-i) exp(.1) 4 5]

% Assignment via colon operator
c = 0:10
d = 5:-1:1
e = 2:3:10
f = 1:0.3:5
g = (0:.1:1)*pi

% Assignment with linspace
h = linspace(1,2,10) % 10 equally spaced points between 1 and 2
k = linspace(2,3,11) % 11 equally spaced points between 2 and 3

% Assignment with logspace
l = logspace(1,2,6) % 6 equally spaced points between 10^1 and 10^2
m = logspace(-5,-1,11) % 11 equally spaced points between .00001 and .1
Arrays may also be constructed by concatenating other arrays or parts of arrays. For example,
% Concatenating arrays
n = [a b] % construct a new array out of previous arrays a and b
m = [b(3:5) a(1:3)] % construct an array using pieces of a and b

% Even trickier (can you figure this one out?)
o = [1 2 a(1:2:3)]
So far, we've only constructed arrays that are row vectors. Soon we'll see that we often need arrays that are column vectors as well. Remember how column vectors are defined from Section 1.4.1?
% Constructing column arrays (explicit assignment)
p = [1; 2; 5; 4; 3]
q = [4
But that's a pain. What about using linspace and logspace? Do they make only row vectors? Yes, but...
next up previous contents
Next: 3.2 Manipulating matrices and Up: 3. More on matrices Previous: 3. More on matrices   Contents
Gus Hart 2005-01-28