4.3: Creating and Indexing a 2D Array

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    4.3: Creating and Indexing a 2D Array

    The most common way to create a matrix in MATLAB is to type the values inside square brackets. Values in the same row are separated by spaces or commas. Rows are separated by semicolons.

    mat1 = [4, 3, 1; 3, 8, 6]
    mat2 = [2 10 5; 6 20 17; 13 2 0]

    The first matrix has 2 rows and 3 columns. The second matrix has 3 rows and 3 columns. It is often helpful to line up the entries visually when you type a matrix, especially when the matrix has several rows:

    mat2 = [ 2  10   5;
             6  20  17;
            13   2   0 ];

    MATLAB does not require the extra spaces, but spacing can make your code easier to read.

    Common mistake

    Every row of a matrix must have the same number of elements. If one row has 3 values and another row has 4 values, MATLAB cannot create a rectangular 2D array.

    Using the Colon Operator to Create Rows

    The colon operator can also be used inside a matrix. This is convenient when the rows follow a pattern.

    Example \(\PageIndex{1}\)
    mat3 = [2:5; 3:6]
    Solution

    The first row is created from 2 through 5, and the second row is created from 3 through 6. Both rows have four elements, so MATLAB can combine them into a matrix.

    mat3 =
    
       2   3   4   5
       3   4   5   6

    Indexing in 2D Arrays

    Indexing means referring to a specific part of an array. For a 2D array, we use two indices: one for the row and one for the column.

    Example \(\PageIndex{2}\)

    Indexing a 2D array.

    mat1 = [4, 3, 1; 3, 8, 6];
    number = mat1(1,3)
    Solution

    This asks MATLAB for the value in row 1, column 3. In this case, the answer is 1.

    Remember: In MATLAB, matrix indexing is row first, column second: matrix(row, column).

    For example, in matrix mat2, the value 17 is in row 2, column 3.

    Column 1

    Column 2

    Column 3

    Row 1

    2

    10

    5

    Row 2

    6

    20

    17

    Row 3

    13

    2

    0


    This page titled 4.3: Creating and Indexing a 2D Array was last modified on Tue, 30 Jun 2026 02:11:56 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.