创建和操纵MATLAB®数组,包括使用索引访问元素。
MATLAB将所有类型的数据存储在数组中。这不仅包括数字数据,还包括其他类型的数据,例如字符串甚至复杂的对象。因此,使用阵列对于与MATLAB合作至关重要。使用MATLAB语言,您可以使用许多索引方法创建数组,访问和分配值,并执行许多其他操作来操纵数组的内容。
让我们首先看创建数组。您可以通过使用方括号和逗号或空格指定特定值来创建一个数组,以分离一行中的列,例如等于1、2、3、4和半隆以分开行。您可以使用等列运算符(例如1到10)等于1到10的列量阵列,在2的步骤中等于1至10,或者在2的步骤中等于10到1。
Linspace空间功能与结肠操作员相似,让您指定一个开始和终点值,但可以控制诸如7的点数。您可以使用转置操作员将行更改为列。您还可以调用许多功能,这些函数生成具有不同内容的基本矩阵,例如零,零或随机数。通过将其打开到变量编辑器中检查数组的内容可能更方便。
Let's now look at how you can access and change the values of array elements with different forms of indexing. You can specify elements of an array by simple row and column indexing. Here is the element of A in the first row second column.
您可以指定一系列行和列以访问数组的各节,例如第1行,第1至2列2。元素不必连续,例如第1行1和第3列。您可以指定所有行或所有行列使用结肠操作员,在这种情况下指定所有列。您还可以使用终点关键字,例如第1行,第2列到末端或2端负1。
You can assign values to specific elements by specifying indexing on the left hand side of the equation such as rows 1, columns 2 to the end minus 1 equals 10 10. You can delete one or more rows of an array such as rows 1 to 2, all the columns, by assigning them to the empty matrix denoted by square brackets. A is now two rows shorter.
Sometimes it is convenient to treat two dimensional arrays such as these as a one dimensional array as though all the columns were stacked together into a single column and specify single index. This is called linear indexing. For example, the element at row 1 column 2 can be accessed through one linear index, 5.
这是可能的因为MATLAB数组存储column wise in memory. In other words, each column in the array is stored one after another. So the element at row 1 column 2 is, in fact, the fifth element stored. The colon operator used on its own specifies all elements when using linear indexing, and it returns a single column vector with the entire array contents.
您还可以使用所谓的逻辑索引访问元素,其中指定填充有真或错误值的索引数组,例如掩码。这对于在值匹配某些标准(例如A)的元素上操作很有用,该元素小于0.5,这会创建一个逻辑值的数组,与AN在此显示的真实值相同,每当A小于0.5时,此处显示为1。注意逻辑值(如True和Fals)分别显示为1和0。
我们可以使用诸如此类的逻辑数组来执行逻辑索引,例如设置A的元素,其中A的元素小于0.5至负1。要找到与您的标准匹配的数组元素的索引,请使用查找功能,以找到非 -零值与逻辑表达式一起。这给出了符合条件A的元素的线性索引小于0.5。您可以改用行和列索引。您可以在文档中查看有关所有索引技术的信息。
最后,让我们看一下如何提取有关数组的一些有用信息并执行一些基本操作。您可以在数组上获取基本信息,例如确定它是否为空,获取长度(通常用于1D数组) - 所有尺寸的大小或元素总数。正如我们之前看到的,使用方括号创建数组使我们可以水平或垂直地将许多数组串在一起。其他有用的数组操纵功能包括翻转左右和上向下的翻转,repmat以复制矩阵,重塑和排序。
Although the examples shown here use one and two dimensional arrays, most of these techniques can be applied to multi-dimensional arrays, as well. See the documentation for more information. This concludes the demonstration. Try these features in MATLAB now or watch one of the other videos.
Featured Product
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:。
You can also select a web site from the following list:
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.