Getting Started with MATLAB | Search  Help Desk |
Other Data Structures
This section introduces you to some other data structures in MATLAB, including:zeros
, ones
, rand
, or randn
with more than two arguments. For example
R = randn(3,4,5);creates a 3-by-4-by-5 array with a total of 3x4x5 = 60 normally distributed random elements. A three-dimensional array might represent three-dimensional physical data, say the temperature in a room, sampled on a rectangular grid. Or, it might represent a sequence of matrices, A(k), or samples of a time-dependent matrix, A(t). In these latter cases, the (i, j)th element of the kth matrix, or the tkth matrix, is denoted by
A(i,j,k)
.
MATLAB's and Dürer's versions of the magic square of order 4 differ by an interchange of two columns. Many different magic squares can be generated by interchanging columns. The statement
p = perms(1:4);generates the 4! = 24 permutations of
1:4
. The k
th permutation is the row vector, p(k,:)
. Then
A = magic(4); M = zeros(4,4,24); for k = 1:24 M(:,:,k) = A(:,p(k,:)); endstores the sequence of 24 magic squares in a three-dimensional array,
M
. The size of M
is
size(M) ans = 4 4 24It turns out that the 22nd matrix in the sequence is Dürer's:
M(:,:,22) ans = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1The statement
sum(M,d)computes sums by varying the
d
th subscript. So
sum(M,1)is a 1-by-4-by-24 array containing 24 copies of the row vector
34 34 34 34and
sum(M,2)is a 4-by-1-by-24 array containing 24 copies of the column vector
34 34 34 34Finally,
S = sum(M,3)adds the 24 matrices in the sequence. The result has size 4-by-4-by-1, so it looks like a 4-by-4 array,
S = 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204Cell arrays in MATLAB are multidimensional arrays whose elements are copies of other arrays. A cell array of empty matrices can be created with the
cell
function. But, more often, cell arrays are created by enclosing a miscellaneous collection of things in curly braces, {}
. The curly braces are also used with subscripts to access the contents of various cells. For example
C = {A sum(A) prod(prod(A))}produces a 1-by-3 cell array. The three cells contain the magic square, the row vector of column sums, and the product of all its elements. When
C
is displayed, you see
C = [4x4 double] [1x4 double] [20922789888000]This is because the first two cells are too large to print in this limited space, but the third cell contains only a single number, 16!, so there is room to print it. Here are two important points to remember. First, to retrieve the contents of one of the cells, use subscripts in curly braces. For example,
C{1}
retrieves the magic square and C{3}
is 16!. Second, cell arrays contain copies of other arrays, not pointers to those arrays. If you subsequently change A
, nothing happens to C
.
Three-dimensional arrays can be used to store a sequence of matrices of the same size. Cell arrays can be used to store a sequences of matrices of different sizes. For example,
M = cells(8,1); for n = 1:8 M{n} = magic(n); end Mproduces a sequence of magic squares of different order,
M = [ 1] [ 2x2 double] [ 3x3 double] [ 4x4 double] [ 5x5 double] [ 6x6 double] [ 7x7 double] [ 8x8 double]
M{4}Enter text into MATLAB using single quotes. For example,
s = 'Hello'The result is not the same kind of numeric matrix or array we have been dealing with up to now. It is a 1-by-5 character array. Internally, the characters are stored as numbers, but not in floating-point format. The statement
a = double(s)converts the character array to a numeric matrix containing floating-point representations of the ASCII codes for each character. The result is
a = 72 101 108 108 111The statement
s = char(a)reverses the conversion. Converting numbers to characters makes it possible to investigate the various fonts available on your computer. The printable characters in the basic ASCII character set are represented by the integers
32:127
. (The integers less than 32 represent nonprintable control characters.) These integers are arranged in an appropriate 6-by-16 array with
F = reshape(32:127,16,6)';The printable characters in the extended ASCII character set are represented by
F+128
. When these integers are interpreted as characters, the result depends on the font currently being used. Type the statements
char(F) char(F+128)and then vary the font being used for the MATLAB command window. On a PC or Mac, select Preferences under the File menu. Be sure to try the Symbol and Wingdings fonts, if you have them on your computer. Here is one example of the kind of output you might obtain.
!"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\]^_ 'abcdefghijklmno pqrstuvwxyz{|}~ °¢£§·¶ß®©´¨¦ÆØ ×±ð ¥µ¹²³¼½ªº¾æø ¿¡¬ÐÝý«» þÀÃÕ ""`'÷ÞÿY/¤ __ · ÂÊÁËÈÍÎÏÌÓÔ ÒÚÛÙ ~¯ °¸" ÿConcatenation with square brackets joins text variables together into larger strings. The statement
h = [s, ' world']joins the strings horizontally and produces
h = Hello worldThe statement
v = [s; 'world']joins the strings vertically and produces
v = Hello worldNote that a blank has to be inserted before the
'w'
in h
and that both words in v
have to have the same length. The resulting arrays are both character arrays; h
is 1-by-11 and v
is 2-by-5.
To manipulate a body of text containing lines of different lengths, you have two choices - a padded character array or a cell array of strings. The char
function accepts any number of lines, adds blanks to each line to make them all the same length, and forms a character array with each line in a separate row. For example
S = char('A','rolling','stone','gathers','momentum.')produces a 5-by-9 character array
S = A rolling stone gathers momentum.There are enough blanks in each of the first four rows of
S
to make all the rows the same length. Alternatively, you can store the text in a cell array. For example
C = {'A';'rolling';'stone';'gathers';'momentum.'}is a 5-by-1 cell array
C = 'A' 'rolling' 'stone' 'gathers' 'momentum.'You can convert a padded character array to a cell array of strings with
C = cellstr(S)and reverse the process with
S = char(C)Structures are multidimensional MATLAB arrays with elements accessed by textual field designators. For example,
S.name = 'Ed Plum'; S.score = 83; S.grade = 'B+'creates a scalar structure with three fields.
S = name: 'Ed Plum' score: 83 grade: 'B+'Like everything else in MATLAB, structures are arrays, so you can insert additional elements. In this case, each element of the array is a structure with several fields. The fields can be added one at a time,
S(2).name = 'Toni Miller'; S(2).score = 91; S(2).grade = 'A-';Or, an entire element can be added with a single statement.
S(3) = struct('name','Jerry Garcia',... 'score',70,'grade','C')Now the structure is large enough that only a summary is printed.
S = 1x3 struct array with fields: name score gradeThere are several ways to reassemble the various fields into other MATLAB arrays. They are all based on the notation of a comma separated list. If you type
S.scoreit is the same as typing
S(1).score, S(2).score, S(3).scoreThis is a comma separated list. Without any other punctuation, it is not very useful. It assigns the three scores, one at a time, to the default variable
ans
and dutifully prints out the result of each assignment. But when you enclose the expression in square brackets,
[S.score]it is the same as
[S(1).score, S(2).score, S(3).score]which produces a numeric row vector containing all of the scores.
ans = 83 91 70Similarly, typing
S.namejust assigns the names, one at time, to
ans
. But enclosing the expression in curly braces,
{S.name}creates a 1-by-3 cell array containing the three names.
ans = 'Ed Plum' 'Toni Miller' 'Jerry Garcia'And
char(S.name)calls the
char
function with three arguments to create a character array from the name
fields,
ans = Ed Plum Toni Miller Jerry Garcia