其他数据结构

其他数据结构

这部分介绍给你在MATLAB中的一些其他数据结构,包括

(1)数学队列

(2)元胞队列

(3)字符和文本

(4)结构

一、数学队列

在MATLAB中数学队列是带有超过l两个下标的队列。创建一个数学队列的一个方式是通过调用zeros,ones,rand,或randn超过两个自变量。例如:

R = randn(3,4,5);

创建一个3*4*5队列总共是3*4*5 = 60通常是随机分布元素。

一个三维队列能够表示三维物理数据,说明在一个房间中的温度,在一个长方格子上的样本。否则它应该表示一个矩阵的序列,A(k),或一个时间-发展矩阵的样本,A(t),在那些最新的事件,(i,j)th Kth矩阵的元素,或tkth矩阵,是通过A(i,j,k)表示。

命令4不同的魔方的MATLAB和Dürer的版本通过一个两列的互换。许多不同的魔方能够通过互换列产生。陈述:

p = perms(1:4);

产生4! = 24,1:4的排列。kth排列是行向量p(k,:)。然后

A = magic(4);
M = zeros(4,4,24);
for k = 1:24
   M(:,:,k) = A(:,p(k,:));
end

在一个三维队列中存储24魔方的序列,M。M的尺寸是:

size(M)

ans =
     4     4    24


注意:在这个插图中矩阵的命令显示可能与你的结果不同。perms函数允许结果所有输出向量的排列,但是排列的命令可能不同与不同的MATLAB版本有关。

陈述

sum(M,d)

计算和通过变化dth下标。因此

sum(M,1)

是一个1*4*24队列包含24各行向量的复制

34    34    34    34

sum(M,2)

是一个4*1*24队列包含24个列向量的复制

34   
34   
34   
34

最后,

S = sum(M,3)

在序列中相加24个矩阵。结果大小4*4*1,因此它和一个4*4队列相似。

S =
   204   204   204   204
   204   204   204   204
   204   204   204   204
   204   204   204   204

 

二、元胞队列

在MATLAB中元胞队列是多位队列其元素是其他队列的复制。空矩阵的A元胞队列能够被cell函数创建。但是,反而常常,元胞队列在卷括号中被附上一个繁杂的事件集合。卷括号也是用于下标去存取各种元胞的内容。例如

C = {A sum(A) prod(prod(A))}

产生一个1*3元胞队列。三个元胞魔方,列的和的行向量,并且所有它的元素的产生。当C显示,你看

C =
    [4x4 double]    [1x4 double]    [20922789888000]

这是因为首先在这个有限的空间中两元胞太大而不能去打印,但是第三个元胞仅仅含有一个单精度数值,16!,因此那里有空间去打印它。

给你两个重点去记住。首先,检索元胞的一个的包含,在卷括号中使用下标。例如,C{1}检索魔方和C{3}是16.第二点,元胞队列包含其他队列的复制,不指向其他队列。如果你随后更改A,C不会放生任何更改。

你能够使用三维队列去存储一个相同尺寸的矩阵的序列。元胞队列能够被用于存储一个不同尺寸的矩阵的序列。例如,

M = cell(8,1);
for n = 1:8
   M{n} = magic(n);
end
M

产生一个不同命令的魔方的序列。

M =
    [           1]
    [ 2x2  double]
    [ 3x3  double]
    [ 4x4  double]
    [ 5x5  double]
    [ 6x6  double]
    [ 7x7  double]
    [ 8x8  double]


你能够检索我们的老朋友:

M{4}

三、文字和文本

确定文本进入MATLAB使用单精度引用。例如,

s = 'Hello'

结果和数值矩阵或队列不同,你已经分配了。它是一个1*5的字符队列。

内部,文字是作为数字存储,但是不是在浮点格式中。陈述:

a = double(s)

转换字符队列为一个数值矩阵含有ASCII代码的浮点表示,为每个字符。结果是:

a =
    72    101    108    108    111

陈述

s = char(a)

逆向转换

在你的计算机上再生数字到文字使它可能去探讨各种现有字体。在基础ASCII字符设置中屏显字符是通过整数32:127代表。(整数小于32代表非屏显控制字符。)在一个适当6*16队列中这些整数排列为:

F = reshape(32:127,16,6)';

在扩展ASCII字符设置中屏显字符是通过F+128代表。当这些整数被翻译为字符,结果取决于在字体上现存通用。类型陈述:

char(F)
char(F+128)

然后不同字体通用到命令窗口。选择偏好设置从文件菜单到选择字体。如果你在行中包括代码标号,使用一个固定宽度字体,例如Monospaced,到排列标号位置在不同行上。

并列方括号加入文本变量一起到更大的扩张。陈述:

h = [s, ' world']

加入水平扩张然后产生

h =
   Hello world

陈述

v = [s; 'world']

添加水平扩张然后产生

v =
   Hello
   world

注意:在h中那是一个空白插入'w'之前并且在v中那是两个不得不相同的长度的词。结果队列是两个字符队列;h是1*11而v是2*5。

操纵一个文本部分包含不同长度的扩张,你有两个字符--一个装填字符队列或一个扩张的元胞队列。当创建一个字符队列,你必须使队列的每行长度相同。(使用空格装填元素位置使其与其他行长度相同。)char函数帮你完成装填。例如:

S = char('A','rolling','stone','gathers','momentum.')

产生一个5*9字符队列。

S =
A       
rolling 
stone   
gathers 
momentum.

交替的,你能够在一个元胞队列中存储文本。例如,

C = {'A';'rolling';'stone';'gathers';'momentum.'}

创建一个5*1元胞队列,其不需要装填,因为队列的每行长度能够互不同。

C =
    'A'
    'rolling'
    'stone'
    'gathers'
    'momentum.'

你能够覆盖一个装填字符队列到一个扩张的元胞队列:

C = cellstr(S)

然后逆向处理:

S = char(C)

四、结构

结构是通过校勘学指定带有元素存取的多位MATLAB队列。例如,

S.name = 'Ed Plum';
S.score = 83;
S.grade = 'B+'

创建一个带有三个范畴的标量

S =
     name: 'Ed Plum'
    score: 83
    grade: 'B+'

在MATLAB中像一切其他结构是队列,因此你能够插入附加元素。在这个事件中,每个队列的元素是一个带有几个范畴的结构。范畴能够增加一个在一个时间内。

S(2).name = 'Toni Miller';
S(2).score = 91;
S(2).grade = 'A-';

或一个整体元素能够以一个单精度结构被增加。

S(3) = struct('name','Jerry Garcia',...
               'score',70,'grade','C')

现在大型充足的结构,仅仅一个摘要被印刷。

S =
1x3 struct array with fields:
    name
    score
    grade

那有几个方式进入其他MATLAB队列调整各种范畴。它们所有以一个逗号分开的列表符号为基础。如果你键入:

S.score

它和键入的相同

S(1).score, S(2).score, S(3).score

这是一个逗号分开的列表。没有任何其他标点,它不是非常有用。它分配三个得分,同时,默认变量求解和定义打印输出每个任务的结果。但是当你在方括号中附上表达式,

[S.score]

它和这个相同,

[S(1).score, S(2).score, S(3).score]

产生一个数字行向量含有所有的得分。

ans =
    83    91    70

类似,键入

S.name

刚分配名称,同时,求解。但是在卷括号中附上表达式,

{S.name}

创建一个包含三个名称的1*3元胞队列

ans =
    'Ed Plum'    'Toni Miller'    'Jerry Garcia'

char(S.name)

调用char函数带有三个论点,从名称范畴创建一个字符队列,

ans =
Ed Plum   
Toni Miller
Jerry Garcia

定义范畴名称

在一个结构中访问数据多数常见方法是通过指定你想要参考的范畴的名称。另外存取结构数据的工具是使用能动范畴名称。那些名称表示范畴为一个在实时中MATLAB评价的变量表达式。点括号语法显示了那里使表达一个能动范畴名称。

structName.(expression)

索引到这个范畴使用MATLAB索引语法的结构。例如,去评价表达式进入一个范畴名称和得到其在列7的行1到行25范畴的变量,使用

structName.(expression)(7,1:25)

能动范畴名称示例。avgscore函数显示下面计算一个平均测验得分,从校验得分结构检索信息使用能动范畴名称。

function avg = avgscore(testscores, student, first, last)
for k = first:last
   scores(k) = testscores.(student).week(k);
end
avg = sum(scores)/(last - first + 1);

你能够为能动范畴student运行这个函数使用不同的变量。

avgscore(testscores, 'Ann Lane', 1, 20)
ans =
   83.5000

avgscore(testscores, 'William King', 1, 20)
ans =
   92.1000

Other Data Structures

This section introduces you to some other data structures in MATLAB, including

(1)Multidimensional Arrays

(2)Cell Arrays

(3)Characters and Text

(4)Structures

一、Multidimensional Arrays

Multidimensional arrays in MATLAB are 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 3x4x5 = 60 normally distributed random elements.< /FONT >

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 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< /FONT >

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

Note    The order of the matrices shown in this illustration might differ from your results. The perms function always returns all permutations of the input vector, but the order of the permutations might be different for different MATLAB versions.

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 different 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]

You can retrieve our old friend with

M{4}

三、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)';< /FONT >

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. Select Preferences from the File menu to change the font. 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 into larger strings. The statement

h = [s, ' world']

joins the strings horizontally and produces

h =
   Hello world

The statement

v = [s; 'world']

joins the strings vertically and produces

v =
   Hello
   world

Note 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. 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 strings with

C = cellstr(S)

and reverse the process with

S = char(C)

四、Structures

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
    grade

There 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.score

it is the same as typing

S(1).score, S(2).score, S(3).score

This 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 the scores.

ans =
    83    91    70

Similarly, typing

S.name

just assigns the names, one at a 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

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:

avgscore(testscores, 'Ann Lane', 1, 20)
ans =
   83.5000

avgscore(testscores, 'William King', 1, 20)
ans =
   92.1000

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值