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

配列の複数の要素を参照するにはコロン (:) 演算子を使用します。これにより、'start:end' の形式で要素の範囲を指定できます。

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