Beginner digital Mode-matlab Quick start! Part II

Source: Internet
Author: User
Tags mathematical functions

Let's start with a picture:

The painting was painted by the German painter Albrecht Dürer, which was filled with mathematical symbols. In the upper right window, you will find that it is a matrix. We'll start here.

So, what is the avatar of the matrix that appears in this painting?

In fact, this matrix is called Magic Square, because each row of his line, the main diagonal and the diagonal number of the sum of all equal, and are (1+16) *2=34.

(said microblogging network red, art science writers, advertising dog Gu Yu also spent a lot of time in the "small gu chat painting," introduced lost master, interested in children's shoes can go over, personal feeling pretty good)

So let's put it into MATLAB.

A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]

Hint: Try the other input methods introduced in the first chapter!

Now that you can see it in the workspace (workspace), we can refer to it directly using the variable name a.

Now let's introduce several basic MATLAB functions:

1. Sum function sum: Sums each column of the matrix, such as SUM (A), with the result of:

Ans= 34 34 34 34

Now ans is already a vector of four columns in a row.

If you do not specify which variable the output value is stored in, MATLAB will temporarily save the result in the ANS variable.

Q: Think of several ways to find the sum of each line of matrix A?

Hint: Check the official documentation for the SUM function, with the command: Doc Sum

2. Transpose matrix A ': Returns a transpose matrix of matrix A, such as the run result of a ':

Ans = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1

Hint: Try B=a ' This command in the command line!

3. Flip function FLIPLR: Swap the first column of the matrix with the last column, the second column and the penultimate column ... Space is limited, here is no longer demo FLIPLR (a) ~

4. Diagonal array Diag: Take the main diagonal element as a vector.

Hint: Try Sum (diag (FLIPLR (A)))!

5. Generate Magic square Magic function : such as B = Magic (4), MATLAB will return to you a satisfying condition of the magic side:

B = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1

Hint: Now that both Matrix B and matrix A satisfy the nature of magic square, what is the difference between the two matrices?

In MATLAB, you have three ways to get a matrix:

1. Manual input

2. Read in the mat file

3. Through the MATLAB function (in addition to the own function, you can also define some functions yourself!) ) generates

Among them, the most commonly used is the first and the third kind.

MATLAB also has many useful matrix constructors, such as: Zeros, ones, Rand, RANDN, perms, and so on.

Hint: Remember to check the official information of the find function below.


variable Name: It is said that the variable name of MATLAB is case-sensitive, and the variable name length should not be greater than 63 characters (certainly enough).

>>n = Namelengthmax>>n = 63


numbers : MATLAB supports the scientific notation and the input of complex numbers (both I and j are imaginary units), and the following numbers are valid:

3-99 0.00019.6397238 1.60210e-20 6.02252e231i-3.14159j 3e5i

     Sometimes, improper storage of numbers can also cause some overflow errors, such as:

MATLAB stores all numbers internally using the long format specified by the IEEE?

Floating-point standard. Floating-point numbers have a finite precision of roughly

Significant decimal digits and a finite range of Rou Ghly 10-308 to 10+308.

The

Numbers represented in the double format has a maximum precision of% bits. Any

Double requiring the more bits than loses some precision. For example, the following code

shows and unequal values to be equal because they is both truncated:

X = 36028797018963968;

y = 36028797018963972;

X = = y

Ans =

1

Integers have available precisions of 8-bit, 16-bit, 32-bit, and 64-bit. Storing the same

numbers as 64-bit integers preserves precision:

x = UInt64 (36028797018963968);

y = UInt64 (36028797018963972);

X = = y

Ans =

0

Here, x==y indicates "x and Y are equal". Returns 1 if equal, otherwise returns 0.

Here's a look at the built-in sort functionin matlab sort: matlab handles all numbers as a complex number, so each number has its phase angle (that is, the angle to the x-axis). The sort function is sorted according to the priority of "modulo long, then phase", for example:

>> sort ([3+4i, 4+3i,6+8i,5,6]) ans = Columns 1 through 4 5.0000 + 0.0000i 4.0000 + 3.0000i 3.0000 + 4.0000i 6.0000 + 0.0000i Column 5 6.0000 + 8.0000i

You can query the phase angle through the angle function:

>> Angle (3+4i) ans = 0.9273

This is, of course, stored in radians.


About the basic operation of the Matrix, the author in the Matlab Quick start the first article has been written, details please see here ? http://my.oschina.net/bgbfbsdchenzheng/blog/501141

These operations are particularly handy when constructing matrices, such as:

>> n = (0:9) ';>> pows = [n n.^2 2.^n]pows = 0 0 1 1 1 2 2 4 4 3 9 8 4 16 16 5 25 32 6 36 64 7 49 128 8 64 256 9 81 512


     function : In the MATLAB library, the function is more than thousands. The author can not be introduced individually. But the official documents are quite detailed:

For a list of The elementary mathematical Functions, type

help Elfun  %you would see you is familiar with some of them, such as Sin,cos,exp. ..

For a list of further advanced mathematical and matrix functions, type

help Specfun

help Elmat

Some of the functions, like sqrt and sin, is built in. Built-in functions is part of the

MATLAB core so they is very efficient, but the computational details is not Readily

accessible. Other functions is implemented in the MATLAB programing language, so

Their computational details is accessible.

There is some differences between built-in functions and other functions. For example,

For built-in functions, you cannot see the code. For other functions, you can see the code

And even modify it if you want.

There are also predefined constants:

If you let a non-0 value divide by 0, or get a value greater than the maximum allowable value of MATLAB (approximately 10^308),Matlab is likely to return you an INF. Some numbers that cannot be expressed mathematically, such as Inf-inf or 0/0, are Nan.

However, you can even temporarily change these constants

>> pi = 4pi = 4 This time pi is a temp variable >> clear pi% clear change to pi >> Pians = 3.1416



Sometimes we need matlab to display numbers in a specific format. So, how to change the number format in MATLAB?

     is simple, using the Format command is fine.

x = [4/3 1.2345e-6]format short   % The simplest short type     1.3333  0.0000format short e    % scientific notation, showing the same number of significant digits as short      1.3333e+000 1.2345e-006format short g    % priority to use short, use scientific notation when necessary      1.3333 1.2345e-006format long    %long type, output more digits      1.33333333333333 0.00000123450000format long e    %% Scientific Counting method, The number of significant digits shown is the same as long     1.333333333333333e+000 1.234500000000000e-006format long  g    % takes precedence over long and uses scientific notation when necessary     1.33333333333333 1.2345e-006format  bank    % reserved two decimal places     1.33 0.00format rat     % to the nearest fraction     4/3 1/810045format hex    % hexadecimal output     3ff5555555555555 3eb4b6231abfd271 

Hint: If you think these formats are not enough, you can even use fprintf and sprintf functions to customize the format!


Having said so much, how do you do a whole row of delete operations ? In fact, it is very simple, you can assign it to empty!

A (2,:) = []% delete second row A (:, 3) = []% delete second column

You can also play this way:

A (1:2,2:3) = 0 The second to third column element of line first to second is set to 0 respectively

Logical Operations : We can operate on specific elements, even if we do not know their subscripts now, but only need to satisfy certain logical conditions (such as "is real", "is the prime number", etc.).

Now there is such a vector:

x = [2.1 1.7 1.6 1.5 NaN 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8];

If we want to get rid of Nan, and then remove the "outlier" 5.1, we can do this:

x = x (isfinite (x)) x = 2.1 1.7 1.6 1.5 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8x = x (ABS (X-mean (x)) <= 3*std (x))%st D (x) indicates the standard deviation of x = 2.1 1.7 1.6 1.5 1.9 1.8 1.5 1.8 1.4 2.2 1.6 1.8


find function : Very simple, such as to replace the prime element in a with Nan, you can do this:

>> a = magic (4) a =    16     2      3    13     5    11     10     8     9      7     6    12     4     14    15     1>> isprime (A) ans  =     0     1     1      1     1     1      0     0     0     1      0     0     0      0    &nbSp;0     0>> find (IsPrime (A)) ' Ans =     2      5     6     7      9    13 >> a (k)  = NaNA =     16   NaN   NaN   NaN   NaN    NaN    10     8     9    NaN     6    12     4     14    15     1


Now we can create magic square for ourselves.

p = perms (1:4);    % generates a combination sequence of 4!=24 1-4 (1 2 3 4, 2 3 4 1), etc. a = Magic (4); m = zeros (4,4,24); for k = 1:24 m (:,:, k) = A (:, p (k,:)); end% at this time M is the "union" of 24 4*4 magic squares, is a three-dimensional array. Now let's look at the size of M: >>size (m) ans = 4 4 24



Finally, the array of cells and the structure :

An array of cells (cell array) is a basket, everything can be loaded into the →_→ just remember to use curly braces {} when the definition.

>>c = {A sum (a) prod (prod (a))}%a is a magic square,prod function that is produce of, used to multiply C = [4x4 double] [1x4 double] [209227898 88000]

You can also use a cell to define an array of cells, as follows:

M = cell (8,1); % defines a 8 row 1-column cell array for n = 1:8 M{n} = Magic (n); endmm = [1] [2x2 double] [3x3 double] [4x4 double] [5x5 D Ouble] [6x6 double] [7x7 double] [8x8 double]


To select a fourth "cell" from, just enter m{4}:

>> M{4}ans = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1


Here's how the primary structure operates:

in MATLAB, you don't even need to define a struct to assign a value directly to it :

S.name = ' Ed Plum '; S.score = 83; S.grade = ' B + '% view now S>>SS = Name: ' Ed Plum ' score:83 grade: ' B + '

Again, define a:

S (2). Name = ' Toni Miller '; S (2). score = 91; S (2). Grade = ' A-'; S (3) = struct (' name ', ' Jerry Garcia ',... ' score ', ' d ', ' Grade ', ' C ')% now this struct array is already too large, so it will not be displayed directly on the screen s = 1x3 struct array with Fields:name score Grade

Now we want all the grade in S:

>> S.grade% with S (1). Score, S (2). Score, S (3). Score same ans = B+ans = A-ans = C

Let's make a fuss about score:

>>scores = [S.score]% extract all score in S to scores scores = $ >>avg_score = SUM (scores)/length (scores) Avg_score = 81.3333

The name element is the same

>>names = char (s.name) names = ed Plum Toni Miller Jerry Garcia >>names = {s.name}names = ' ed Pl Um ' Toni Miller ' Jerry Garcia ' >>[n1 N2 N3] = S.namen1 = Ed PlumN2 = Toni MillerN3 = Jerry Garcia



All right, here we go today. Say the latest competition one by one, last weekend because of college students have no more, this week's weekend is the ACM Beijing Regional Competition Online game, next weekend is Hefei regional competition, so it is estimated that another few days not more, well that is the case. = =

Beginner digital Mode-matlab Quick start! Part II

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.