Androidnote's Matrix Introduction

Source: Internet
Author: User

The protagonist matrix of this article is a model worker who has been working silently in the background, although we all see the matrix behind the view of the credit, but we seldom see it, this article we will see where it is sacred.

As Google has already done a good job of packaging this part, so skip this part of the actual development impact is not too large, do not want to delve into the rough view, the next article will be detailed on the matrix of the specific usage and skills.

?? Warning: Turn off hardware acceleration before you test this article example.
Matrix Introduction

Matrices are a matrix, the main function is coordinate mapping, numerical conversion.

It might look like this:

Matrix is a coordinate mapping, so why do you need a matrix? To give a simple example:

My phone screen as a physical device, its physical coordinate system starts from the upper left corner, but we usually do not use this coordinate system at the time of development, but instead use the coordinate system of the content area.

For example, our content area and screen coordinate system also differ from one notification bar and a title bar distance, so the two are not coincident, we in the content area in the coordinate system of the final drawing of the content must be converted to the actual physical coordinate system to draw, the role of the matrix here is to convert these values.

Assuming that the notification bar is 20 pixels tall and the navigation bar height is 40 pixels, we draw a point at the (0,0) position in the content area and eventually convert to a point in the actual coordinate system (0,60).

The above is only as a simple example, in fact, whether 2D or 3D, we want to display graphics on the screen, can not be separated from the matrix, so that the matrix is a hard work in the back of the workers.

Matrix Features

Wider scope, matrix in the view, pictures, animation effects and other aspects of the use, compared with the previous explanation and other canvas operation wider application.
More flexible, the canvas operation is the package of the Matrix, the matrix as a closer to the bottom of things, must be more flexible than the canvas operation.
The package is good, the matrix itself is a good package for each method, so that developers can easily operate the matrix.
Difficult to understand deeply, it is difficult to understand the meaning of the various values, as well as the rules of operation, if you do not understand the matrix, it is difficult to understand the previous multiplication.
Common misconceptions

1. It is considered that the three parameters (Mpersp_0, mpersp_1, mpersp_2) of the Matrix's bottom line are not much of a function here, just for the sake of dine.

In fact, the last row of parameters plays a critical role in the 3D transformation, which is described in detail in the following camera article.

2. The last parameter mpersp_2 is interpreted as scale

It is true that changing the value of mpersp_2 can achieve a scale-like effect, but this is because of the homogeneous coordinates, not the actual function of this parameter.

Matrix Fundamentals

Matrix, the most fundamental function of which is the transformation of coordinates, let's look at the principles of several common transformations:

All of the transformations we use are affine transformations, which are the composite of linear transformations (scaling, rotation, tangent) and translational (translational), since these concepts are not very useful to us, but they are more interesting to understand.
There are 4 basic transformations: panning (translate), scaling (scale), rotation (rotate), and error-cutting (skew).

Let's take a look at the parameters that are controlled by each of the four transformations.

From the last three parameters can be seen to control the perspective, these three parameters are mainly used in the 3D effect, usually (0, 0, 1), not in the scope of this discussion, not too much to describe, will later in the article detailed its role.

Since most of our calculations are based on matrix multiplication rules, if you have returned the linear algebra to the teacher, please refer here: wikipedia-matrix multiplication

1. Scaling (Scale)

Represented by a matrix:

You may have noticed that we have a 1 more coordinates, which is the reason for using the homogeneous coordinate system, in mathematics our points and vectors are represented in this way (x, y), the two look the same, the computer cannot differentiate, for this reason the computer can also differentiate them, add a flag bit, and then it looks like this:

(x, Y, 1)-point
(x, y, 0)-Vector

In addition, homogeneous coordinates have the properties of equal ratio, (2,3,1), (4,6,2) ... (2n,3n,n) represents the point (2,3). (The misconception that mpersp_2 is interpreted as scale stems from this).
Legend:

2. Wrong Cut (Skew)

There are two kinds of special error cut, horizontal error cutting (parallel x axis) and vertical error cutting (parallel y axis).

Horizontal Error Cutting

Represented by a matrix:

Legend:

Vertical Error Cutting

Represented by a matrix:

Legend:

Compound Error Cutting

A combination of horizontal and vertical dislocation.

Represented by a matrix:

Legend:

3. Rotation (Rotate)

Assume a point a (x0, y0), the distance from the origin is r, the angle of the horizontal axis is α, the θ is rotated around the origin, and the rotation is point B (x, y) as follows:

Represented by a matrix:

Legend:

4. Pan (Translate)

Here is one of the advantages of using homogeneous coordinates, in fact, the previous three operations using a 2x2 matrix can also meet the requirements, but using a 2x2 matrix, the translation operation can not be added to it, and the coordinates are expanded to the sub-coordinates, the matrix can be extended to 3x3 to unify the algorithm, Each of the four algorithms can be completed using matrix multiplication.

Represented by a matrix:

Legend:

Matrix Composite principle

In fact, many of the matrix of composite operations are implemented using matrix multiplication, the principle of understanding is very simple, but the use of matrix multiplication also has its weaknesses, the subsequent operations may affect the front to the operation, so in the construction of the Matrix when the order is very important.

We used four major transformations, each operation in the matrix has three categories, the pre-multiply (pre), post-multiply (post) and set (set), you can see at the end of the matrix method table, because matrix multiplication does not meet the Exchange law, so the pre-multiply (pre), post-multiply (post) and set (set) The difference is still very big.

Pre-multiply (pre)

The forward multiplication is the right multiplication of the matrix:

This represents a matrix with a special matrix before the multiplication of the result matrix.
Back Multiply (POST)

The front multiplication is the same as the left multiply of the matrix:

This represents a matrix with a special matrix followed by multiply after the result matrix is constructed.
Setting (SET)

Instead of using matrix multiplication, the setting overrides the original value directly, so the use of the setting may result in the previous operation being invalidated.

Combination

One problem with the Matrix article is that the theory of the pre and post section is very awkward, and most articles in the country are like this, seemingly right but difficult to understand, and partly counterintuitive.

I have also been influenced by these articles, and have inherited this theory naturally, until a small partner in the comment area raised a question that allowed me to revisit this part of the story and have some reflection.

After a long thought, I decided to abandon most of the domestic articles of the set of theories and conclusions, only with rigorous mathematical logic and procedural logic to explain this part of the theory, perhaps there are omissions, please correct me if found.

First clarify two false conclusions, remember, are false conclusions, false conclusions, false conclusions.

Error conclusion One: The pre is sequential execution, and post is executed in reverse order.

This conclusion is confusing because the conclusion is not completely wrong, and you can easily prove it, such as the following:

First pre-order execution, first translation (T) after rotation (R)
Matrix matrix = new Matrix ();
Matrix.pretranslate (Pivotx,pivoty);
Matrix.prerotate (angle);
LOG.E ("Matrix", matrix.toshortstring ());

Second post reverse order, translate (T) after rotation (R)
Matrix matrix = new Matrix ();
Matrix.postrotate (angle);
Matrix.posttranslate (Pivotx,pivoty)
LOG.E ("Matrix", matrix.toshortstring ());
The final result of these two pieces of code is equivalent, so it is easy to prove the correctness of this conclusion, but is it true?

First, from a mathematical point of view, the pre and post are the difference between right-or left-multiply, and secondly, they cannot actually affect the order of operations (program execution order). These two pieces of code are equivalent only because the final formula is the same.

The original matrix is M, the translation is T, the rotation is R, the unit matrix is I, the final result is M '

Matrix multiplication does not satisfy the commutative law, i.e. a*b≠b*a
Matrix multiplication satisfies the binding law, i.e. (a*b) \c = A (b*c)
The matrix multiplied by the unit matrix results in the same result, i.e. A * I = a
Since the original matrix (M) in the example above is a unit matrix (I), it is possible to:

First stage Pre
M ' = (Mt)r = Itr = T*r

Second segment Post
M ' = t(rM) = trI = T*r
Because the two final formulas are the same, the two are equivalent, but the conclusion is not universal.

That is, the original matrix is not a unit matrix, the two can not be reduced to the same formula, the result will naturally be different. In addition, the order of execution is the sequence of program writing, there is no so-called positive sequence reverse order.

Error conclusion Two: The pre is executed first, while Post is executed.

This conclusion is more outrageous than the previous one.

The reason for this error is that the person who wrote the article knows English.

Pre: First, similar to before.
Post: After, similar to after.
So it came to the pre-execution, and after post to execute this statement, but from the rigorous mathematical and procedural aspects of the analysis, is completely impossible, or the above, the pre and post can not affect the program execution sequence, and the program every execution of a statement will produce a definite result, so, It has no control over the execution, and it belongs to the completely ripped type.

If you have to use this theory to force the explanation, it looks like the post is executed first, for example:

Matrix.prerotate (angle);
Matrix.posttranslate (Pivotx,pivoty);
Same simplification formula:

Matrix multiplication satisfies the binding law
M ' = t(Mr) = tmr = (tm)R
In fact, the matrix multiplication satisfies the binding law, so whether you say it is done on the right or on the left first, there is nothing wrong with the result.

Based on this error, I had a false proof:

(This content is destined to be my writing process can not be wiped out of the shame, since it is a public article, it should be responsible for the reader, although I published every article before all efforts to verify the problems, various details, to avoid such errors, but after all, left behind such a piece of content, I sincerely to all of my readers apologize. )

Follow my readers as much as I can in my personal blog and GitHub release, these two platforms are within the blog repair program, there are any errors or flaws, will first repair the two platform articles. In addition, all of the articles that have been repaired will be re-posted on my Weibo @GcsSloop, and follow my tweets to get updates or fixes for the first time.

The following is an error proof:

In practice, we get accurate results for every step of the operation, but why do we have to use a sequential argument? Is it really possible to use pre and post to influence the order of calculations? In fact, we use an example to illustrate the following:

Matrix matrix = new Matrix ();
Matrix.postscale (0.5f, 0.8f);
Matrix.pretranslate (1000, 1000);
LOG.E (TAG, "matrixtest" + matrix.toshortstring ());
In the above operation, if the normal way of thinking, the first scaling, after panning, the scaling operation before the execution, will not affect the subsequent panning operation, but the execution results found that the translation distance into (500, 800).

In the above example, the calculation order is no problem, the calculation of the scale, and then the translation of the calculation, and the scaling effect to the translation is because the result matrix of the previous step is scaled to the right by the translation matrix, which is consistent with the matrix multiplication of the Operation law, that is, the scaling operation has affected the translation operation, This is equivalent to performing a panning operation and then performing a scaling operation, so that the pre operation is performed first, and the post operation executes this statement.

The above argument is completely wrong, because the inverse example can be easily cited:

Matrix matrix = new Matrix ();
Matrix.prescale (0.5f, 0.8f);
Matrix.pretranslate (1000, 1000);
LOG.E (TAG, "matrixtest" + matrix.toshortstring ());
In the inverse case, although the Postscale is changed to Prescale, but the results are identical, so the theory of succession is simply wrong.

They're the same because the final formula is the same, it's all s*t.

The translation distance is mtrans_x = 500,mtrans_y = 800, because the Matrix already has a scaling scale before executing the Translate. When the right multiplier affects the specific numerical calculation, it can be calculated by matrix multiplication.

The end result is:

When t*s, the scale does not affect mtrans_x and mtrans_y, which can be calculated by using matrix multiplication.

How do I understand and use pre and post?

Don't go into the theory of succession, order theory, according to the most basic matrix multiplication understanding.

Pre: Right multiply, m ' = MA
Post: Left multiply, m ' = A
m
So how to use it?

The correct way to use it is to construct the normal Matrix multiplication sequence, and then use the pre and post to implement the order.

Or in the simplest case, let's say that you need to rotate around a certain point.

You can use this method xxxrotate (angle, Pivotx, pivoty), because we need to combine a Matrix here, so we don't use this method directly.

First, there are two basic theorems:

All operations (rotate, pan, zoom, and Err) are by default the datum point of the coordinate origin.
The coordinate system state of the previous operation is preserved and affects subsequent states.
Based on these two fundamental theorems, we can deduce that the following steps are required to rotate based on a point:

    1. First move the coordinate system origin to the specified position, using the pan T
    2. Rotate the coordinate system using the rotation S (rotate around the origin)
    3. Then translate the coordinate system back to its original position using the pan-t
      The specific formula is as follows:

M is the original matrix, is a unit matrix, M ' is the result matrix, T is the translation, R is the rotation
M ' = mtR-t= tr*-t
The pseudo-code written by the formula is as follows:

Matrix matrix = new Matrix ();
Matrix.pretranslate (Pivotx,pivoty);
Matrix.prerotate (angle);
Matrix.pretranslate (-pivotx,-pivoty);
Around a certain point of action can be extended to a common situation, namely:

Matrix matrix = new Matrix ();
Matrix.pretranslate (Pivotx,pivoty);
Various operations, rotation, scaling, error cutting, etc., can be executed multiple times.
Matrix.pretranslate (-pivotx,-pivoty);
The formula is:

M ' = MT ... - t = t ... *-t
But in this way, the translation function of the two adjustment centers is too open, so this is usually used:

Matrix matrix = new Matrix ();
Various operations, rotation, scaling, error cutting, etc., can be executed multiple times.
Matrix.posttranslate (Pivotx,pivoty);
Matrix.pretranslate (-pivotx,-pivoty);
This formula is:

M ' = Tm ... - t = t ... *-t
You can see that the result is the same as the final simplification.

So, the pre and post are used to adjust the multiplication order, normally we should construct the multiplication order formula, then adjust the writing according to the actual situation.

In the construction of the Matrix, personal advice to use a multiplication, pre-or post-multiply, so that the sequence of operations is easy to determine, the problem is easier to troubleshoot. Of course, since the matrix multiplication does not satisfy the commutative law, the results of the pre-multiplication and the post-multiplication are different and should be used in combination with the specific scenario analysis.

Here we construct the same matrix in different ways:

Attention:

1. Since matrix multiplication does not satisfy the commutative law, ensure that the initial matrix (Initial matrix) is used, otherwise it may result in a different operation.
2. Note the construction order, which can affect the result.
The 3.Initial matrix refers to the new matrix, or the matrix after reset, which is a unit matrix.
1. Use the Pre only:

Using Pre, M ' = MTS = t*s
Matrix M = new Matrix ();
M.reset ();
M.pretranslate (TX, Ty);
M.prescale (SX, SY);
Represented by a matrix:

2. Use post only:

Using post, M ' = TSm = t*s
Matrix M = new Matrix ();
M.reset ();
M.postscale (SX, SY); , the more forward the more first to execute.
M.posttranslate (TX, Ty);
Represented by a matrix:

3. Mixing:

Mixed m ' = TmS = t*s
Matrix M = new Matrix ();
M.reset ();
M.prescale (SX, SY);
M.posttranslate (TX, Ty);
Or:

Mixed m ' = TmS = t*s
Matrix M = new Matrix ();
M.reset ();
M.posttranslate (TX, Ty);
M.prescale (SX, SY);
Because there are only two steps here, and the order is specified successively, the exchange on the code does not affect the result.
Represented by a matrix:

Note: Since matrix multiplication does not satisfy the commutative law, ensure that the initial matrix is the unit matrix, and that if the initial matrix is not a unit matrix, the result of the operation is different.

Although the above uses a lot of different wording, but the final formula is the same, these different formulations, are based on the same formula in reverse.

Matrix Method Table

This method table, temporarily put here to let everyone see, the method of using the explanation in the next article.

Method category Related API summary
Basic method equals Hashcode toString toshortstring Compare, get hash value, convert to String
Numeric operation set reset Setvalues getValues set, reset, set value, get value
Numerical calculation mappoints Mapradius maprect mapvectors calculation of the transformed values
Set (set) Setconcat setRotate setscale Setskew settranslate Set transform
Front multiply (pre) Preconcat prerotate Prescale preskew pretranslate front Multiply transform
Post-multiply (post) postconcat postrotate Postscale Postskew posttranslate post-multiply transform
Special methods Setpolytopoly Setrecttorect Rectstaysrect Setsincos some special operations
Matrix correlation invert isaffine isidentity inverse matrix, whether it is affine matrix, is the unit matrix ...
Summarize

For the matrix to understand and understand the principles behind it will be more handy to use.

After finishing this article, we recommend that with the big video course to create a personalized picture preview and multi-touch consumption, you will be able to understand the matrix to a higher level.

Due to the limited personal level, the article may be wrong, if you feel that part of the error, or found typos and other content, welcome to tell me in the comment area, in addition, it is said that the attention of the author is not only the first time to receive new articles news, but also to become handsome oh.

Androidnote's Matrix Introduction

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.