Matrix library c windows

Matrix Класс

Определение

Инкапсулирует аффинное представление с матричным преобразованием 3 на 3, представляющим геометрическое преобразование. Encapsulates a 3-by-3 affine matrix that represents a geometric transform. Этот класс не наследуется. This class cannot be inherited.

Комментарии

В GDI+ можно сохранить аффинное преобразование в Matrix объекте. In GDI+ you can store an affine transformation in a Matrix object. Поскольку третий столбец матрицы, представляющий аффинное преобразование, всегда имеет значение (0, 0, 1), при создании объекта в первых двух столбцах указывается только шесть чисел Matrix . Because the third column of a matrix that represents an affine transformation is always (0, 0, 1), you specify only the six numbers in the first two columns when you construct a Matrix object. Оператор Matrix myMatrix = new Matrix(0, 1, -1, 0, 3, 4) конструирует матрицу, показанную на следующем рисунке. The statement Matrix myMatrix = new Matrix(0, 1, -1, 0, 3, 4) constructs the matrix shown in the following figure.

Составные преобразования Composite Transformations

Составное преобразование — это последовательность преобразований, в одну за которой следуют другие. A composite transformation is a sequence of transformations, one followed by the other. Рассмотрим матрицы и преобразования в следующем списке: Consider the matrices and transformations in the following list:

Матрица A Matrix A Поворот на 90 градусов Rotate 90 degrees
Матрица B Matrix B Масштабирование по коэффициенту 2 в направлении по оси x Scale by a factor of 2 in the x direction
Матрица C Matrix C Переводить 3 единицы по оси y Translate 3 units in the y direction

Если начать с точки (2, 1), представленной матрицей [2 1 1]-и умножить на, то B, затем C, точка (2, 1) пройдет три преобразования в указанном порядке. If we start with the point (2, 1) — represented by the matrix [2 1 1] — and multiply by A, then B, then C, the point (2, 1) will undergo the three transformations in the order listed.

[2 1 1] ABC = [-2 5 1] [2 1 1]ABC = [-2 5 1]

Вместо того чтобы хранить три части составного преобразования в трех отдельных матрицах, можно умножить, B и C, чтобы получить одну матрицу размером 3 × 3, которая хранит все составное преобразование. Rather than store the three parts of the composite transformation in three separate matrices, you can multiply A, B, and C together to get a single 3×3 matrix that stores the entire composite transformation. Предположим, ABC = D. Затем точка, умноженная на D, дает тот же результат, что и точка, умноженная на, а затем на B, а затем на C. Suppose ABC = D. Then a point multiplied by D gives the same result as a point multiplied by A, then B, then C.

[2 1 1] D = [-2 5 1] [2 1 1]D = [-2 5 1]

На следующем рисунке показаны матрицы A, B, C и D. The following illustration shows the matrices A, B, C, and D.

Тот факт, что матрица составного преобразования может быть сформирована путем умножения единичных матриц преобразования, означает, что любая последовательность аффинных преобразований может храниться в одном Matrix объекте. The fact that the matrix of a composite transformation can be formed by multiplying the individual transformation matrices means that any sequence of affine transformations can be stored in a single Matrix object.

Порядок составного преобразования важен. The order of a composite transformation is important. Как правило, поворот, масштабирование, преобразование не не отличается от масштабирования, затем поворота и преобразования. In general, rotate, then scale, then translate is not the same as scale, then rotate, then translate. Аналогично, важен порядок умножения матриц. Similarly, the order of matrix multiplication is important. Как правило, ABC не совпадает с БПЗ. In general, ABC is not the same as BAC.

MatrixКласс предоставляет несколько методов для создания составного преобразования: Multiply , Rotate . RotateAt Scale Shear и Translate . The Matrix class provides several methods for building a composite transformation: Multiply, Rotate, RotateAt, Scale, Shear, and Translate. В следующем примере создается матрица составного преобразования, которая сначала поворачивает 30 градусов, затем масштабируется по коэффициенту 2 в направлении по оси y, а затем преобразует 5 единиц в направлении по оси x: The following example creates the matrix of a composite transformation that first rotates 30 degrees, then scales by a factor of 2 in the y direction, and then translates 5 units in the x direction:

Читайте также:  Как посмотреть список установленных пакетов линукс

Конструкторы

Инициализирует новый экземпляр класса Matrix в виде единичной матрицы. Initializes a new instance of the Matrix class as the identity matrix.

Инициализирует новый экземпляр класса Matrix для геометрического преобразования, определяемого указанным прямоугольником и массивом точек. Initializes a new instance of the Matrix class to the geometric transform defined by the specified rectangle and array of points.

Инициализирует новый экземпляр класса Matrix для геометрического преобразования, определяемого указанным прямоугольником и массивом точек. Initializes a new instance of the Matrix class to the geometric transform defined by the specified rectangle and array of points.

Инициализирует новый экземпляр класса Matrix указанными элементами. Initializes a new instance of the Matrix class with the specified elements.

Свойства

Возвращает массив значений с плавающей запятой, представляющий элементы этого объекта Matrix. Gets an array of floating-point values that represents the elements of this Matrix.

Возвращает значение, определяющее, является ли объект Matrix единичной матрицей. Gets a value indicating whether this Matrix is the identity matrix.

Возвращает значение, указывающее, является ли матрица Matrix обратимой. Gets a value indicating whether this Matrix is invertible.

Возвращает значение смещения по оси X (значение dx, или элемент на пересечении третьей строки и первого столбца) объекта Matrix. Gets the x translation value (the dx value, or the element in the third row and first column) of this Matrix.

Возвращает значение смещения по оси Y (значение dy, или элемент на пересечении третьей строки и второго столбца) для этого объекта Matrix. Gets the y translation value (the dy value, or the element in the third row and second column) of this Matrix.

Методы

Создает точную копию данного объекта Matrix. Creates an exact copy of this Matrix.

Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Унаследовано от MarshalByRefObject) Dispose()

Освобождает все ресурсы, используемые этим объектом Matrix. Releases all resources used by this Matrix.

Проверяет, является ли заданный объект объектом Matrix и идентичен ли он объекту Matrix. Tests whether the specified object is a Matrix and is identical to this Matrix.

Позволяет объекту попытаться освободить ресурсы и выполнить другие операции очистки, перед тем как он будет уничтожен во время сборки мусора. Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.

Возвращает хэш-код. Returns a hash code.

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) InitializeLifetimeService()

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) Invert()

Обращает матрицу Matrix, если она обратима. Inverts this Matrix, if it is invertible.

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) MemberwiseClone(Boolean)

Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.

(Унаследовано от MarshalByRefObject) Multiply(Matrix)

Умножает эту матрицу Matrix на матрицу, указанную в параметре matrix , путем добавления перед указанной матрицей Matrix. Multiplies this Matrix by the matrix specified in the matrix parameter, by prepending the specified Matrix.

Читайте также:  Виртуальная машина unix для windows

Умножает этот объект Matrix на матрицу, указанную в параметре matrix , в порядке, задаваемом в параметре order . Multiplies this Matrix by the matrix specified in the matrix parameter, and in the order specified in the order parameter.

Сбрасывает этот объект Matrix, чтобы получить элементы единичной матрицы. Resets this Matrix to have the elements of the identity matrix.

Добавляет в этот объект Matrix поворот по часовой стрелке вокруг начала координат на указанный угол. Prepend to this Matrix a clockwise rotation, around the origin and by the specified angle.

Применяет поворот по часовой стрелке вокруг начала координат (нулевые координаты X и Y) на величину, указанную в параметре angle , к этому объекту Matrix. Applies a clockwise rotation of an amount specified in the angle parameter, around the origin (zero x and y coordinates) for this Matrix.

Применяет поворот по часовой стрелке к этому объекту Matrix; поворот производится вокруг точки, указанной в параметре point , и путем добавления поворота в начало. Applies a clockwise rotation to this Matrix around the point specified in the point parameter, and by prepending the rotation.

Применяет поворот по часовой стрелке вокруг указанной точки к объекту Matrix в указанном порядке. Applies a clockwise rotation about the specified point to this Matrix in the specified order.

Применяет указанный вектор масштабирования к этому объекту Matrix, добавляя вектор масштабирования в начало. Applies the specified scale vector to this Matrix by prepending the scale vector.

Применяет указанный вектор масштабирования ( scaleX и scaleY ) к этому объекту Matrix в указанном порядке. Applies the specified scale vector ( scaleX and scaleY ) to this Matrix using the specified order.

Применяет указанный вектор сдвига к этому объекту Matrix, добавляя преобразование сдвига в начало. Applies the specified shear vector to this Matrix by prepending the shear transformation.

Применяет указанный вектор сдвига к этому объекту Matrix в указанном порядке. Applies the specified shear vector to this Matrix in the specified order.

Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.

(Унаследовано от Object) TransformPoints(Point[])

Применяет геометрическое преобразование, представляемое этим объектом Matrix, к указанному массиву точек. Applies the geometric transform represented by this Matrix to a specified array of points.

Применяет геометрическое преобразование, представляемое этим объектом Matrix, к указанному массиву точек. Applies the geometric transform represented by this Matrix to a specified array of points.

Применяет только компоненты масштабирования и поворота этого объекта Matrix к указанному массиву точек. Applies only the scale and rotate components of this Matrix to the specified array of points.

Умножает каждый вектор массива на матрицу. Multiplies each vector in an array by the matrix. Элементы смещения данной матрицы (третья строка) игнорируются. The translation elements of this matrix (third row) are ignored.

Применяет указанный вектор смещения ( offsetX и offsetY ) к этому объекту Matrix, добавляя вектор смещения в начало. Applies the specified translation vector ( offsetX and offsetY ) to this Matrix by prepending the translation vector.

Применяет указанный вектор смещения к этому объекту Matrix в указанном порядке. Applies the specified translation vector to this Matrix in the specified order.

Умножает каждый вектор массива на матрицу. Multiplies each vector in an array by the matrix. Элементы смещения данной матрицы (третья строка) игнорируются. The translation elements of this matrix (third row) are ignored.

Matrix library c windows

A lightweight matrix library for c.

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio

Latest commit

Git stats

Files

Failed to load latest commit information.

readme.md

This file contains a brief description of the main functions provided by the library. More details about these functions can be found here http://cristid9.github.io/libMatrix/files.html.

This is is a minimalist matrix library which provides support for basic mathematical operations like:

  • addition of 2 matrices
  • multiplication with a scalar
  • multiplication of 2 matrices
  • computing the trace
  • computing the transpose
  • computin the determinant
  • computing the minorants of a matrix
  • computing the inverse
  • raising a matrix to a given power
Читайте также:  What is dropbear linux

It also provides some uility function that will make your life easier in with the data structures of the library:

  • creating a matrix
  • destroying a matrix
  • printing a matrix(to the stdout)
  • reading a matrix(from the stdin)
  • copying a matrix
  • comparing matrices

Building the library

To build the library you need to run the following commands:

Creating a matrix

In order to create a matrix you need to include the matrix.h header file:

After you have done this you need to declare a pointer to a Matrix and assign to it the value returned by create_matrix . The function create_matrix takes 2 arguments: the number of rows and the number of columns. This is how you create a 2 by 2 matrix.

The call to destroy_matrix is used to release the memory allocated for foo .

Compiling a source file

To compile a source file that uses the matrix library you need to dynamically link the library. This is how you will compile the file from the previous section:

Please remember to add -lm after -lMatrix .

Accessing properietes of a matrix

A matrix has some proprietes that you should care about:

This is how you will access these proprites:

Muliplication of a matrix with a scalar

In order to multiply a matrix with a scalar you will need to use the multiply_matrix_with_scalar function. This function takes 2 arguments: the matrix and the scalar to multiply that matrix with. The only issue of this function is that it modifies the value of the original matrix.

This is how you will do this:

Computing the minorant of a matrix

You will use get_minor to do this job, which takes 3 arguments: the matrix, the line and the column that will be eliminated for the minorant. It returns a pointer to a Matrix which is the minorant. After you hae finished with the minorant and you do not need it anymore you need to destroy it.

Computing the transpose of a matrix

The function that does this is called get_transpose and it takes 2 arguments the matrix, and a pointer to a matrix where the transpose will be initialized. This function returns an error status.

Computing the inverse of a matrix

The function that does this is called compute_inverse and will just set the inverse member of the matrix you want to compute the inverse of.

This is how you will compute the inverse of a matrix called foo:

You do not have to care about releasing the memory allocated to foo. destroy_matrix will do this for you.

Computing the determinant of a matrix

This operation is very simillar with the previous one. The function that does this is called get_determinant and takes only one argument, the matrix you want to compute the determinant of and it just sets the determinant member of that matrix.

This is how you will compute the determinant of a matrix:

Multiplying 2 matrices

In order to multiply 2 matrices you need to have a third variable where the result will be stored.

This is how you multiply 2 matrices a and b .

Adding 2 matrices

This is very simillar with the process of multiplying 2 matrices.

Copying a matrix

Say you want to copy the value of a matrix foo to a matrix bar . This is how you do it:

Raising a matrix to a power

This is done with the function matrix_pow , which takes as arguments the matrix and the power to raise that matrix to. The function will return a pointer to the result.

Comparing 2 matrices

In order to comper 2 matrices you will use the function compare_matrices which returns true if the matrices have the same elemnts and false otherwise. Boolean types are not suported in c89, we encourage you to use the c99 standard.

Оцените статью