Main Content

访问数组元素

此示例说明如何使用索引访问选定的数组元素。

创建一个幻方矩阵,它由 1 到 16 的整数构成且总行数和总列数相等。

disp('Create 4-by-4 magic square a:')
disp('>> a = magic(4)')
a = magic(4)
Create 4-by-4 magic square a:
>> a = magic(4)

a =

    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

要引用数组中的某特定元素,请使用以下语法指定其行号和列号,其中 A 是矩阵变量。请始终先指定行,后指定列。

disp('Reference element in row 4, column 2:')
disp('>> a(4, 2)')
a(4, 2)
Reference element in row 4, column 2:
>> a(4, 2)

ans =

    14

要引用数组的多个元素,请使用冒号“:”运算符,该运算符允许您使用“开始:结束”形式指定元素范围。

disp('List the elements in the first three rows and the second column of a:')
disp('>> a(1:3, 2)')
a(1:3, 2)
List the elements in the first three rows and the second column of a:
>> a(1:3, 2)

ans =

     2
    11
     7

单独的冒号(没有起始值或结束值)指定该维度中的所有元素。

disp('Select all the columns in the third row of a:')
disp('>> a(3, :)')
a(3, :)
Select all the columns in the third row of a:
>> a(3, :)

ans =

     9     7     6    12