Create a matrix in Matlab

Defining a matrix in Matlab is very simple. I assign a name to the matrix and write the rows of the matrix separated by a semicolon and the individual elements separated by a space or a comma in square brackets . $$ A=[a11\:\: a12\:\: a13; \\ \:\:\:\:\:\:\:\:\:\: a21\:\: a22\:\:a23; \\ \:\:\:\:\:\:\:\:\:\: a31\:\:a32\:\:a33; ] $$

    A practical example

    I define a 2x3 rectangular matrix with 2 rows and 3 columns.

    $$ M = \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix} $$

    The matrix has two rows:

    1. The first row consists of the elements 1,2,3
    2. The second row consists of the elements 4,5,6

    Note. The elements of each line must be separated by a space or a comma. Space is definitely easier.

    So, to create the matrix I write the two lines separated by the semicolon

    M = [row1;row2]

    In this case

    M = [ 1 2 3 ; 4 5 6 ]

    The result is a matrix consisting of two rows and three columns.

    Example 2

    I create a 3x3 square matrix with three rows and three columns

    $$ M = \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{pmatrix} $$

    In this case there are three lines

    1. The first row consists of the elements 1,2,3
    2. The second row consists of the elements 4,5,6
    3. The third row consists of the elements 7,8,9

    So, to define the matrix I write

    M = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]

    I have separated the elements with a space.

    I could also have defined the matrix by separating the elements with a comma.

    M = [ 1, 2, 3 ; 4, 5, 6 ; 7, 8, 9 ]

    The result would have been the same.

    However, in my opinion, the comma reduces the readability of the code

     


     

    Segnalami un errore, un refuso o un suggerimento per migliorare gli appunti

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Appunti su MATLAB

    Simulink

    Le alternative open source a Matlab