matlab基本操作2
-
Types of Arrays
-
Multidimensional Arrays
-
arrays with more than two subscripts. One way of creating a multidimensional array is by calling 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 345 = 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 tk th matrix, is denoted by A(i,j,k). MATLAB 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 kth 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,:)); end stores the sequence of 24 magic squares in a three-dimensional array, M. The size of M is size(M) ans = 4 4 24
The statement
sum(M,d)
computes sums by varying the dth subscript. So
sum(M,1)
is a 1-by-4-by-24 array containing 24 copies of the row vector
34 34 34 34
and
sum(M,2)is a 4-by-1-by-24 array containing 24 copies of the column vector
34
34
34
34
Finally,
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 204
-
-
Cell Arrays
-
Cell 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.You can use three-dimensional arrays to store a sequence of matrices of the same size.
Cell arrays can be used to store a sequence of matrices of dLfferent sizes. For example,M = cell(8,1); for n = 1:8 M{n} = magic(n); end M produces a sequence of magic squares of different order: M = [ 1] [ 2x2 double] [ 3x3 double] [ 4x4 double] [ 5x5 double] [ 6x6 double] [ 7x7 double] [ 8x8 double]
-
-
Characters and Text
-
Enter text into MATLAB using single quotes. For example,
s = 'Hello'
The result is not the same kind of numeric matrix or array you 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 111
The 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 Command Window. To change the font, on the
Home tab, in the Environment section, click Preferences > Fonts. If you include tabs
in lines of code, use a fixed-width font, such as Monospaced, to align the tab positions on
different lines.
Concatenation with square brackets joins text variables together. The statement
h = [s, ' world']
joins the characters horizontally and producesh = Hello world
The statement
v = [s; 'world']
joins the characters vertically and produces
v =
Hello
world
Notice 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 character vectors. When creating a character
array, you must make each row of the array the same length. (Pad the ends of the shorter
rows with spaces.) The char function does this padding for you. For example,
S = char('A','rolling','stone','gathers','momentum.')
produces a 5-by-9 character array:
S =
A
rolling
stone
gathers
momentum.
Alternatively, you can store the text in a cell array. For example,
C = {'A';'rolling';'stone';'gathers';'momentum.'}
creates a 5-by-1 cell array that requires no padding because each row of the array can
have a different length:
C =
'A'
'rolling'
'stone'
'gathers'
'momentum.'
You can convert a padded character array to a cell array of character vectors withC = cellstr(S)
and reverse the process with
S = char(C)
-
-
Structures
-
Structures are multidimensional MATLAB arrays with elements accessed by textual fieOd
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 the MATLAB environment, 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
grade
There are several ways to reassemble the various fields into other MATLAB arrays. They
are mostly based on the notation of a comma-separated list. If you typeit is the same as typing
S(1).score, S(2).score, S(3).score
which is a comma-separated list.
If you enclose the expression that generates such a list within square brackets, MATLAB
stores each item from the list in an array. In this example, MATLAB creates a numeric row
vector containing the score field of each element of structure array S:
scores = [S.score]
scores =
83 91 70
avg_score = sum(scores)/length(scores)
avg_score =
81.3333
To create a character array from one of the text fields (name, for example), call the char
function on the comma-separated list produced by S.name:
names = char(S.name)
names =
Ed Plum
Toni Miller
Jerry Garcia
Similarly, you can create a cell array from the name fields by enclosing the list-generating
expression within curly braces:
names = {S.name}
names =
'Ed Plum' 'Toni Miller' 'Jerry Garcia'
To assign the fields of each element of a structure array to separate variables outside of
the structure, specify each output to the left of the equals sign, enclosing them all within
square brackets:
[N1 N2 N3] = S.name
N1 =
Ed Plum
N2 =
Toni MillerN3 =
Jerry Garcia
-
-
Dynamic Field Names
-
The most common way to access the data in a structure is by specifying the name of the
field that you want to reference. Another means of accessing structure data is to use
dynamic field names. These names express the field as a variable expression that
MATLAB evaluates at run time. The dot-parentheses syntax shown here makes
expression a dynamic field name:
structName.(expression)
Index into this field using the standard MATLAB indexing syntax. For example, to evaluate
expression into a field name and obtain the values of that field at columns 1 through 25
of row 7, use
structName.(expression)(7,1:25)
Dynamic Field Names Example
The avgscore function shown below computes an average test score, retrieving
information from the testscores structure using dynamic field names:
function avg = avgscore(testscores, student, first, last)
for k = first:last
scores(k) = testscores.(student).week(k);
end
avg = sum(scores)/(last - first + 1);
You can run this function using different values for the dynamic field student. First,
initialize the structure that contains scores for a 25-week period:
testscores.Ann_Lane.week(1:25) = ...
[95 89 76 82 79 92 94 92 89 81 75 93 ...
85 84 83 86 85 90 82 82 84 79 96 88 98];
testscores.William_King.week(1:25) = ...
[87 80 91 84 99 87 93 87 97 87 82 89 ...
86 82 90 98 75 79 92 84 90 93 84 78 81];
Now run avgscore, supplying the students name fields for the testscores structure at
run time using dynamic field names:avgscore(testscores, 'Ann_Lane', 7, 22)
ans =
85.2500
avgscore(testscores, 'William_King', 7, 22)
ans =
87.7500
-
-