preface

As a developer who knows nothing about linear algebra and wants a quick understanding of vectors and matrices, this article is for you.

This article explains vectors and matrices from a developer’s point of view, implemented in TypeScript. Interested developers are welcome to read this article.

vector

Vector is the basic element of linear algebra research. The basic representation method of a group of numbers together is vector, for example: a number: 100, a group of numbers: (25,78,101). One of these sets of numbers can be called a vector, and in this example it is a three-dimensional vector.

The following formula describes a vector.


m ˉ = ( 25 78 31 ) \bar{m} = \left( \begin{matrix} 25 \\ 78 \\ 31 \end{matrix} \right)

So, what’s a set of numbers good for?

Let’s use an example, as shown in the following table:

The serial number Chinese language and literature mathematics English
0 70 80 90

Of the form (0,70,80,90) this group number respectively describes the serial number, Chinese, maths, English, if the group number the order of the Numbers in a transfer order, then expressed the meaning is completely different, each number represents a point in space, is a set of orderly Numbers, so he can be used to describe an orderly.

Scalars: Numbers in vectors are called scalars.

More concepts of vectors

Row vectors and column vectors

  • Row vectors: Scalars arranged horizontally, as shown below


( 3 . 4 ) \left (3,4 \right)

  • Column vectors: Vertical scalars, as shown below


( 5 . 2 ) T \left (5,2, right)^T

The dimension

The number of scalars in a vector, that’s the dimension of this vector.

For example, the vector (3,4) has a dimension of 2

Implement vector

So let’s take a look at what methods we need to implement for vectors based on that.

  • Gets the dimension of the vector
  • Length of vector
  • Gets a specific element of the vector
  • The output vector

Next, let’s implement each of these methods.

  • Create a TS file named:Vector.ts, all the methods used to implement vectors
  • Declare a vector class. In the constructor we declare the parameters we need to pass. A vector is a set of numbers, so we use arrays to represent vectors
export class Vector {
    constructor(private list: number[] = []){}}Copy the code
  • Achieve the vector dimension function:getDimension
    getDimension(): number {
        return this.list.length;
    }
Copy the code
  • Implement the length function of the vector:length
    len = this.getDimension();
Copy the code
  • Implement specific elements of the vector:getItem
    /** * gets the specific element of the vector *@param Index Index of the target element */
    getItem(index: number) :number {
        return this.list[index];
    }
Copy the code
  • Implement the output vector function
    toStr(): string {
        let str = ` `;
        for (let i = 0; i < this.list.length; i++) {
            if(i ! = =this.list.length - 1) {
                str += `The ${this.list[i]}, `;
            } else {
                str += this.list[i]; }}return `Vector(${str}) `;
    }
Copy the code

Basic operations on vectors

There are two basic operations on vectors: vector addition and vector multiplication

Vector addition


( 5 . 2 ) T + ( 4 . 6 ) T = ( 5 + 4 . 2 + 6 ) T = ( 9 . 8 ) T \left (5,2)^T + \left (4,6)^T = \left (5+4,2+6)^T = \left (9,8)^T

As shown above, the addition of two vectors is described, and its calculation rules are as follows:

  • The dimensions of the two vectors that you add must be equal
  • The components of a vector (that is, each number in a vector) are added separately, and the resulting vector is the result of their addition.

Scalar multiplication of vectors

The multiplication of a vector with a scalar is called scalar multiplication.


( 5 . 2 ) T 2 = ( 5 2 . 2 2 ) T = ( 10 . 4 ) T \left (5,2)^T * 2 = \left (5,2,2)^T = \left (10,4)^T

As shown above, it describes the multiplication of vectors and scalars, and its calculation rules are as follows:

  • You take the components of a vector and multiply them by a scalar, and you get the vector.

The dot product of vectors

The product of two vectors is called the dot product of vectors.


( 5 . 2 ) T ( 2 . 6 ) T = 5 2 + 2 6 = 10 + 12 = 22 \left (5,2)^T * \left (2,6)^T = 5*2+2*6 = 10 + 12 = 22

As shown above, vector multiplication is described, and its calculation rules are as follows:

  • When you multiply two vectors, the dimensions have to be the same
  • You multiply the components of the two vectors, add them together, and the resulting scalar is the result of the multiplication

Implement vector operations

We’ve shown you two basic operations on vectors, and now we can derive more from these two basic operations, and we’re going to implement the following function.

  • Vector addition
  • Subtraction of vectors
  • Vector multiplication
  • Vector division
  • Take vector is
  • Vector take negative
  • The dot product of vectors

We will implement the above functions one by one

  • To implement addition:add
    /** * vector addition *@param Another is the vector that needs to be added */
    add(another: Vector): Vector | string {
        // When adding vectors, make sure their dimensions are equal to the current dimension
        if (this.getDimension() === another.getDimension()) {
            const finalList: number[] = [];
            for (let i = 0; i < this.getDimension(); i++) {
                finalList.push(this.getItem(i) + another.getItem(i));
            }
            return new Vector(finalList);
        } else {
            return "Dimensions are not equal and cannot be added."; }}Copy the code
  • Implement subtraction
    /** * vector subtraction *@param another* /
    sub(another: Vector): Vector | string {
        As with addition, the dimensions must be equal
        if (this.getDimension() === another.getDimension()) {
            const finalList: number[] = [];
            for (let i = 0; i < this.getDimension(); i++) {
                finalList.push(this.getItem(i) - another.getItem(i));
            }
            return new Vector(finalList);
        } else {
            return "Dimensions are not equal and cannot be subtracted."; }}Copy the code
  • Realize quantity multiplication operation
    
    /** * the scalar multiplication of vectors *@param K* /
    mul(K: number): Vector {
        const finalList: number[] = [];
        // Rule of vector multiplication: multiply the number by each dimension of the vector
        for (let i = 0; i < this.getDimension(); i++) {
            finalList.push(this.getItem(i) * K);
        }

        return new Vector(finalList);
    }
Copy the code
  • Implement quantitative division operation
    division(K: number): Vector {
        return this.mul(1 / K);
    }
Copy the code
  • I’m going to take positive and negative vectors
    // Take the vector positive, that is, make the components of the vector positive
    pos(): Vector {
        return this.mul(1);
    }

    // Take the vector negative, that is, make the components of the vector negative
    neg(): Vector {
        return this.mul(-1);
    }
Copy the code
  • Implement the dot product of vectors
    dotMul(another: Vector): number | void {
        if (another.getDimension() === this.getDimension()) {
            let final = 0;
            // The method of dot product of two vectors: multiply the elements of each vector by each other and add the results
            for (let i = 0; i < this.getDimension(); i++) {
                final += this.getItem(i) * another.getItem(i);
            }
            return final;
        } else {
            console.log("Two vectors must have the same dimension when they dot."); }}Copy the code

matrix

A matrix is an extension of vectors. A set of vectors can be put together to form a matrix. We can view a matrix from two perspectives: row vectors and column vectors.


A = ( a 11 a 12 a 13 a 14 a 21 a 22 a 23 a 24 a 31 a 32 a 33 a 34 ) A = \left( \begin{matrix} a_{11} & a_{12} & a_{13} & a_{14}\\ a_{21} & a_{22} & a_{23} & a_{24} \\ a_{31} & a_{32} & a_{33} & a_{34} \end{matrix} \right)

As shown above, A 3*4 matrix is described by the mathematical formula: A(m*n)), where M represents its number of rows and n represents its number of columns.

In the above matrix, A11 means it is in row 1 and column 1 of matrix A, a23 means it is in row 2 and column 3 of matrix A, so we usually use AIj to describe an element in the matrix, I means row, j means column.

If we view this matrix in terms of row vectors, it’s going to be made up of three vectors. If we look at this matrix in terms of column vectors, it’s going to be made up of four vectors.

matrices

Let’s look at the methods to implement a matrix: According to the description of the matrix, we can use a two-dimensional array to describe the matrix.

  • Gets the shape of the matrix, and returns a matrix consisting of rows and columns

    • The number of rows is the length of the two-dimensional array
    • The number of columns is the length of the zero array in a two-dimensional array
  • Gets the number of rows of the matrix, and the number of columns of the matrix. Return the number of rows and columns computed in the matrix shape

  • Get the size of the matrix by multiplying the number of rows by the number of columns

  • The length of the matrix, returns the number of rows of the matrix

  • Gets the row vector of a matrix, returning an array of two dimensional arrays at the specified position

  • Gets the column vectors of the matrix

  • Gets a specific element in the matrix

Next, we will implement the above methods one by one.

  • Create the matrix. ts file to implement the Matrix.
  • Create a Matrix class that declares the parameters to be passed to the constructor
export class Matrix {
    constructor(private twoDimArray: number[] []){}}Copy the code
  • Get the shape of the matrix:shape
    /** * matrix shape *@returns [x,y] x row,y column */
    shape(): number[] {
        // The length of the matrix is the number of rows. The dimension of each vector in the matrix is the same as the number of columns, so take the 0 element as the number of columns
        return [this.twoDimArray.length, this.twoDimArray[0].length];
    }
Copy the code
  • Gets the number of rows of the matrixgetRowNumAnd the number of columnsgetColNum
    // Get the number of rows
    getRowNum(): number {
        return this.shape()[0];
    }

    // Get the number of columns in the matrix
    getColNum(): number {
        return this.shape()[1];
    }
Copy the code
  • Get matrix size and length:size
    size(): number {
        const shape = this.shape();
        return shape[0] * shape[1];
    }
    // The length of the matrix, i.e., the number of rows of the matrix
    len = this.getRowNum();
Copy the code
  • Get the row vector of the matrix:rowVector
    rowVector(index: number): Vector {
        return new Vector(this.twoDimArray[index]);
    }
Copy the code
  • Get the column vectors of the matrix:colVector
    colVector(index: number): Vector {
        // Store the elements of the specified column
        const finalList: number[] = [];
        for (let i = 0; i < this.getRowNum(); i++) {
            // Fetch each row of the matrix
            const row = this.twoDimArray[i];
            // Retrieves the specified column in each row and stores it
            finalList.push(row[index]);
        }
        // Return the vector
        return new Vector(finalList);
    }
Copy the code
  • Get the elements in the matrix:getItem
    getItem(position: number[]) :number {
        return this.twoDimArray[position[0]][position[1]];
    }
Copy the code

The basic operations of matrices

Matrix operations can be divided into: matrix and matrix addition, matrix and scalar multiplication, matrix and vector multiplication, matrix and matrix multiplication.

Matrix addition

The addition of matrices to matrices is called matrix addition. T+P=(12579101326217122)+(12345678111347)=(137101315199141330529)T+P = \left( \begin{matrix} 12 & 5 & 7 & 9 \\ 10 & 13 & 2 & 6 \\ 2 & 17 & 1 & 22 \end{matrix} \right) + \left( \begin{matrix} 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 \\ 11 & 13 & 4 & 7 \end{matrix} \right) = \left( \begin{matrix} 13 & 7 & 10 & 13 \\ 15 & 19 & 9 & 14 \\ 13 & 30 & 5 & 29 \end{matrix} \right)T+P=⎝ ⎛12102513177219622⎠ ⎞+⎝ ⎛15112613374487⎠ ⎞= ⎠ ⎞ 131513719301095131429

The above formula describes the operation process of matrix addition, and its operation method is as follows:

  • When you add two matrices they have to be the same size
  • Taking the elements of two matrices and adding them together to form a new matrix is the result of matrix addition.

Matrix multiplication

The multiplication operation between matrices and scalars is called matrix scalar multiplication.


T k = ( 12 5 7 9 10 13 2 6 2 17 1 22 ) 2 = ( 24 10 14 18 20 26 4 12 4 34 2 44 ) T*k = \left( \begin{matrix} 12 & 5 & 7 & 9 \\ 10 & 13 & 2 & 6 \\ 2 & 17 & 1 & 22 \end{matrix} \right) * 2 = \left( \begin{matrix} 24 & 10 & 14 & 18 \\ 20 & 26 & 4 & 12 \\ 4 & 34 & 2 & 44 \end{matrix} \right)

The above formula describes the operation process of matrix and scalar multiplication, and its operation method is as follows:

  • Multiplying each element of a matrix by a scalar to form a new matrix is the result of multiplying the number of matrices.

Matrix times vector

ˉ T ∗ m = (133557) ∗ (12) = (1 + 3 ∗ ∗ 1 2 = 1 + 6 = 73 5 ∗ ∗ 1 + 2 = 3 + 10 = 135 7 ∗ ∗ 1 + 2 = 5 + 14 = 19) T * \ bar = {m} \ left (\ begin {matrix} 1 & 3 \ \ 3 & 5 \ \ & 7 \end{matrix} \right) * \left( \begin{matrix} 1 \\ 2 \end{matrix} \right) = \left( \begin{matrix} 1*1+3*2=1+6=7 \\ 3 * 1 + 5 * 2 = 3 + 10 = 13 \ \ 5 * 7 * 1 + 2 = 5 + 14 = 19 {matrix} \ \ end right) ˉ T ∗ m = ⎝ ⎛ 135357 ⎠ ⎞ ∗ = ⎝ (12) ⎛1∗1+3∗2=1+6=73∗1+5∗2=3+10=135∗1+7∗2=5+14=19⎠ ⎞ The above formula describes the process of multiplying matrices and vectors as follows:

  • When a matrix is multiplied by a vector, the number of columns in the matrix must be equal to the length of the vector
  • Get the row vectors of the matrix, dot each row vector of the matrix with the vectors

Matrix times matrix


T P = ( 1.5 0 0 2 ) ( 0 4 5 0 0 3 ) = ( 1.5 0 + 0 0 = 0 1.5 4 + 0 0 = 6 1.5 5 + 0 3 = 7.5 0 0 + 2 0 = 0 0 4 + 2 0 = 0 0 5 + 2 3 = 6 ) T*P = \left(\begin{matrix} 1.5&0 \\ 0&2 \end{matrix} \right) * \left(\begin{matrix} 0&4&5\0&0&3) {matrix} \ right) = \ \ end left (\ begin {matrix} 1.5 * * 0 0 + 0 = 0 and 1.5 * 4 + 0 * 0 = 1.5 * 6 & 5 + 0 * 3 = 7.5 \ \ * 0 0 0 = 0 + 2 * & 0 * 4 + 2 * 0 = 0 & 0*5+2*3=6 \end{matrix} \right)

The above formula describes the operation process of matrix multiplication, and its operation method is as follows:

  • When multiplying matrices by matrices, the number of columns in the first matrix must equal the number of rows in the second matrix
  • Split the first matrix into row vectors and the second matrix into column vectors
  • Take the split row vector, dot product with each split column vector, put the returned vector together, and construct the new matrix is the result of the multiplication.

Realize the basic operation of matrix

Next, we use code to implement the above operations.

  • Implement matrix addition operationaddAnd subtractionsub
    /** * add *@param Another another matrix star@return Matrix new Matrix */
    add(another: Matrix): Matrix | void {
        // When two matrices are added, they must be of the same size
        if (this.size() === another.size()) {
            const finalList: number[] [] = [];// Add each element of the matrix to form a new matrix
            for (let i = 0; i < this.getRowNum(); i++) {
                const row: number[] = [];
                for (let j = 0; j < this.getColNum(); j++) {
                    // Add each element
                    row.push(this.getItem([i, j]) + another.getItem([i, j]));
                }
                // Build a new matrix
                finalList.push(row);
            }
            return new Matrix(finalList);
        } else {
            console.log("When you add matrices, they have to be the same size."); }}/** * subtraction *@param Another another matrix star@return Matrix new Matrix */
    sub(another: Matrix): Matrix | void {
        // When two matrices are added, they must be of the same size
        if (this.size() === another.size()) {
            const finalList: number[] [] = [];// Add each element of the matrix to form a new matrix
            for (let i = 0; i < this.getRowNum(); i++) {
                const row: number[] = [];
                for (let j = 0; j < this.getColNum(); j++) {
                    // Add each element
                    row.push(this.getItem([i, j]) - another.getItem([i, j]));
                }
                // Build a new matrix
                finalList.push(row);
            }
            return new Matrix(finalList);
        } else {
            console.log("Matrix subtraction must have the same magnitude."); }}Copy the code
  • Realize matrix number multiplication operationmulAnd divisiondivision
    /** * matrix number multiplication *@param K Target value *@return Matrix new Matrix */
    mul(K: number): Matrix {
        const finalList: number[] [] = [];// Rule of operation: Multiply the elements of each vector by the target number to return a new matrix
        for (let i = 0; i < this.getRowNum(); i++) {
            const row: number[] = [];
            for (let j = 0; j < this.getColNum(); j++) {
                row.push(this.getItem([i, j]) * K);
            }
            finalList.push(row);
        }
        // Build a new matrix and return
        return new Matrix(finalList);
    }

    /** * matrix number division *@param K Target value *@return Matrix new Matrix */
    division(K: number): Matrix {
        return this.mul(1 / K);
    }
Copy the code
  • Implement matrix and vector multiplication:mulVector
    /** * matrix times vector *@param Vector The vector that performs multiplication *@return Vector generates a new Vector */
    mulVector(vector: Vector): Vector | void {
        // The number of columns of a matrix multiplied by a vector must equal the length of the vector
        if (vector.len === this.getColNum()) {
            // Result array
            const finalList: number[] = [];
            // Calculate rules:
            // 1. Multiply each term of the matrix and each term of the vector
            // 2. Add up the results
            // 3. Put the cumulative result into the result array
            // 4. Construct a new vector from the result array
            for (let i = 0; i < this.getRowNum(); i++) {
                // Dot the row vectors of the current matrix with the vectors
                finalList.push(<number>this.rowVector(i).dotMul(vector));
            }
            // Generate a vector based on the result and return it
            return new Vector(finalList);
        } else {
            console.log("When a matrix is multiplied by a vector, the number of columns in the matrix must be equal to the length of the vector."); }}Copy the code
  • Multiply matrices by matrices
    /** * matrix times matrix *@param matrix* /
    mulMatrix(matrix: Matrix): Matrix | void {
        // The number of columns of matrix A must be the same as the number of rows of matrix P
        if (this.getColNum() === matrix.getRowNum()) {
            // The final result is stored in a two-dimensional array
            const finalList = [];
            // Split the two matrices into the dot products between vectors
            for (let i = 0; i < this.getRowNum(); i++) {
                // An array of result row vectors
                const resultList: number[] = [];
                // Get the row vectors of matrix A
                const rowVector = this.rowVector(i);
                for (let j = 0; j < matrix.getColNum(); j++) {
                    // Get the column vectors of the matrix P
                    const colVector = matrix.colVector(j);
                    // Dot the row vectors with the column vectors, placing the result in the array of the resulting row vectors
                    resultList.push(<number>rowVector.dotMul(colVector));
                }
                // Place the constructed result row vector into the two-dimensional array of the final result
                finalList.push(resultList);
            }
            // Build the matrix from the two-dimensional array of the final result
            return new Matrix(finalList);
        } else {
            console.log("Matrix multiplied by matrix, the number of columns in one matrix must equal the number of rows in the other matrix."); }}Copy the code

The code address

For the complete code and test code used in this article, please visit GitHub repository:

Vectors: vector.ts & vectortest.js

Matrix: matrixtest.ts & matrixtest.ts

Write in the last

  • If there are any errors in this article, please correct them in the comments section. If this article helped you, please like it and follow 😊
  • This article was first published in nuggets. Reprint is prohibited without permission 💌