Go to: http://blog.sina.com.cn/s/blog_8354dda801012dyn.html
Viii. visualization of data and functions
I. Description
Matlab as a mathematical software has its powerful graphical user interface operations, data and function visualization and numerical computing functions, and comes with many existing functions and toolkits. This article only deals with some of the basic operations of the comparison system, and at the end comes with a visual command that introduces some basic data and functions. It is recommended to use the Help documentation from MATLAB to search for useful functions and toolkits. MATLAB functions and commands are more user-friendly, for example, want to search the function of reading fits file, search fits can find Fitsread function, need to read out the fits data to do a diagram, search image can be found Imagesc function. From the books and other people's documents can only learn a limited comparison of the operation of the system, see the Help document can find more things and organize their own use of methods.
Ii. data types and basic input and output
The data type (class) stored in MATLAB has the following:
and in fact Matlab does not need to declare the variable, When it finds a new variable name, it defaults to a double-precision floating-point type (double) and allocates memory space. (This is much more convenient than C and Fortran, but it is a waste of storage space for a program that does a large amount of computation)
when you need to convert a variable a from a double to another type, such as to Int16, you can use the following command: A=int16 (a)
When you need to create a character variable x and assign an initial value to it, use the following format: x= ' string ';
Note:
(1) Add ";" After the command Indicates that the result is not displayed in command window, but if not added to the example above. The contents of the assigned string are displayed.
(2) All commands must be in English input state, if you use the Chinese input state full-width ";", will be processed as illegal characters. Where Logical,cell and structure are logical, cellular and schema array types, will be mentioned in the following array section; Function handle is a handler type, which will be mentioned in the "M script file and m function file, function handle" section later; Java class for Java The API application interface is used and is not described in this article. Finally, Matlab also supports the complex operation, the assignment can be entered directly, such as: a=1+2i;
2. Basic input and output
Input: v=input (' message ')% assigns user input to variable v
V=input (' message ', ' s ')% assigns the user input content as a string to the variable V
Keyboard% user can enter any number of instructions from the keyboard
V=yesinput (' Prompt ', default,possib)
%prompt is a text hint, default defaults to "value", and Possib is the range for setting values.
% The directive cannot be run in notebook.
Output: Disp (a)
% Displays the contents of the variable A, and the other way to display the contents of the variable is to enter the variable name, but the result is shown with "a=".
Third, Process Control
1. Operators
(1) relational operator = = ~= > >= < <=
(2) Set of operators involving interrelationships & | ~ XOR% XOR different elements return 1, same element returns 0
2. IF
(1) Basic:
If logic-judged
......
End
(2) Multiple judgments:
If logic-judged
......
else If logical judgment
......
else logical judgment
......
End
End
End
3. The switch-case structure is the same as the C switch statement
Switch variable
Case value 1
......
Case Value 2
......
Case value k% when the variable equals the value K, execute this group of commands and then jump out of the structure.
......
otherwise
...% the command may not exist and execute this set of commands when the variable is not equal to all previous detection values.
End case
4. Try-catch structure
Try% The latter set of commands will be executed only if there is an error in MATLAB executing this group command
......
Catch
...% if this group command executes and is faulted, MATLAB terminates the structure.
End
% can call the LastErr function to query the cause of the error. If the function results in an empty string, the set of commands
was successfully carried out.
Iv. circulation
1. While
While expression
......
End
2. For
For x= value
......
......
End
The value of which can be an array, or a expression like the following "1:4", which represents a loop from 1 to 4, or "1:0.1:4", which indicates that 0.1 is the step from 1 through 4.
V. Arrays, array operations, and matrix operations
1. Array of values
Arrays in MATLAB do not need to be declared.
(1) Assigning an initial value to a one-dimensional numerical array
Input by element: X=[1 2 PI/2]
Colon generation: X=1:0.1:4
Deterministic linear sampling method: X=linspace (A,b,n)
% is equivalent to the first number is a, the last number is B, and N is the sampling point equal to the interval.
X=logspace (A,b,n)
% is equivalent to the first number is 10a, the last number is 10b, and n is the sampling number of points, such as spacing sampling.
(2) Searching for one-dimensional numerical array
X (3)% search for a third element
X ([1 2 3])% search 1th, 2, 3 elements
X (1:3)% search 1th to 3rd element
X (3:-1:1)% is inverted by the first three elements into a subarray
X (Find (x>0.5))% sub-array consisting of elements greater than 0.5
(3) Assigning initial values to two-dimensional numerical arrays
Assign values one by one: x=[1,2,3; 3,4,6; 7,8,9]
%“;” Is the delimiter for a two-dimensional array of "rows", while "," and spaces are delimiters for the same line element.
Full column Assignment: X (:, [4,5]) =4% 4th, 5 columns assigned to 4
Element reflow: A=reshape (1:9,3,3)
% rearrange 1 to 9 into one (3*3) matrix, note that MATLAB is the column "precedence", that is, the first column and then the second column, rather than row by line.
(4) Identification and search of two-dimensional array elements
"Full subscript" identification: A (3,5)% 3rd row 5th column Element
"Single subscript" identifies: for A (m*n)-dimensional array A in the column C of section R, its "single subscript" is expressed as: a (l)% here l= (c-1) *m+r
2. Array operations and matrix operations
(1) Array operation
directive meaning
A. ' Equivalent to Conj (a '), the role of CONJ help ...
A=s assigns a scalar s to each element of a
S+b scalar s and the sum of the B elements respectively
S-b,b-s the difference between the scalar s and the B elements
The product of S.*a scalar s and A element respectively
s./b,b.\s s are divided by the elements of B
Each element of a.^n a squared n times
A.^p a non-integer power to each element of a
The P.^a is based on the p, and the elements of a are exponentially exponentiation.
A+b corresponding elements added
A-b corresponding element subtraction
A.*b corresponding element multiplication
The element of a./b A is removed by the corresponding element of B.
B.\a Ibid.
Exp (a) is based on E, with the element of a as exponential exponentiation
Log (a) logarithm of each element of a
sqrt (a) square root for each element of a
F (a) The function value of each element of a
A#b the relational operations of the corresponding elements, #代表关系运算符
[email protected]The logical operation of the corresponding element, @ represents the logical operator
(2) Matrix operation
directive meaning
A ' conjugate transpose
The product of S*a scalar s and A element respectively
S*INV (b) B-array inverse multiplication s
When a^n a array is a phalanx, squared n times
The non-integer exponentiation of a a^p phalanx
When p^a a array is a square, the matrix of scalar is the exponent
A+b Matrix Addition
Subtract from a-B matrix
A*b matrix multiplication
A/b a right except B
B\a A left except B
Matrix exponential function of expm (a) a
LOGM (a) A's matrix logarithm function
Matrix square root function of Sqrtm (a) a
FUNM (A, ' FN ') General matrix functions
3. Logical array
See the example to understand:
A=zeros (2,5); % pre-build one (2*5) full Zero Group
A (:) =-4:5; % use the "all elements" method to assign a value to a
L=abs (a) >3% produces an array of "0-1" logical values with the same dimension of a
Islogical (l)% determines if L is an array of logical values. If the output is 1, it is
X=a (l)% takes a logical value of 1 for the A element in L
4. Array of strings
(1) Array of strings assigns the initial value s=[' AA ' BB '
Or: S=char (' AA ', ' BB ')
can also: S=str2mat (' AA ', ' ', ' BB ')% here empty string will produce empty line
And: S=str2cat (' AA ', ' ', ' BB ')% here the empty string will not produce a blank line
(2) String manipulation functions
Int2str% converts an array of integers to a string array
Num2str% converts a non-integer array to a string array
Mat2str% converts a numeric array to a string array
% please use Help to search for other string manipulation functions.
5. Cell array
A cell array differs from a general numeric array and an array of strings, and its elements can be objects of any type and size. This
and C's structured array are somewhat similar.
(1) Creating an array of cells
There are two ways to create this:
External identity element Assignment:
A=char (' AA ' BB ');
B=1:9;
C=2:5;
D=[1+2i];
A (+) ={a}; A (={b}); A (2,1) ={c}; A (2,2) ={d};
Direct assignment of connotation:
A=char (' AA ' BB ');
B=1:9;
C=2:5;
D=[1+2i];
A{1,1}=a; A{1,2}=b; A{2,1}=c; A{2,2}=d;
(2) The collection of the contents of the cellular array
Note that the cell is accessed here () and the contents stored in the cell are accessed with {}.
For example: A=a (a)
Display: a=[12 Char]
And: a=a{1,1}
Display: A=aabb
So use {} instead of () to fetch the contents of the cell array.
6. Frame Array
A schema array is similar to an array of cells, but each of its architectures (the cells that are equivalent to the cellular array) must be divided into "domains"
Before you can use it. Look at the following example:
Green_house (2,3). Name= ' room sixth ';
Green_house (2,3). param.temperature=30;
Green_house (2,3). param.humidity=10;
Green_house
Screen display:
A. struct array with fields:
Name
Param
Attention:
(1) The operation of the increment or decrement field on one frame affects the entire array.
(2) The addition or deletion of subdomains does not affect other architectures.
7. Empty array
(1) There are several methods for generating an empty array:
A=[]
The role of B=ones (2,0)%ones was originally to produce an array of all 1
The role of C=zeros (2,0)%zeros was originally to produce an array of all 0
The role of D=eye (2,0)%eye was originally to produce an array with a diagonal element of all 1
The F=rand (2,3,0,4)%rand function was originally generated by the array.
(2) An empty array can be used for the deletion of the subarray and the shrinking of the array size
A (:, 2) =[]
VI, M script file and m function file, function handle
M files are divided into two types: functions and scripts.
The script files do not have input and output to manipulate variables in the workspace (workspace).
any executable matlab command can be written to a script file.
Look at a simple example:
Example 1: produce a one-dimensional random array of 20 elements and draw them.
Solution: Create a new M file named RANDPLT.M (or any name you like), add the following two lines of code:
Data=randn (1,20);
plot (data);
After saving select Debug/run menu or press F5 key to run, observe workspace a variable data. When the
script file executes, it executes sequentially as if each command in the file is entered sequentially into the MATLAB command line. You can try to quickly create an m file by holding down the CTRL key in the Command History window and selecting a few lines of executed commands and right-clicking on the shortcut menu and choosing creat m files.
2, matlab function
The file can accept input and give output, of course, it can not, just like the C language function. The most important writing feature of the MATLAB function (in comparison with C) is that its output variable is defined in front of the function name. Look at an example:
Example 2:matlab internal function STD gives the standard deviation of the array std=sqrt (SUM (x)/n), write the function stderr experiment error
Difference err=sqrt (SUM (x)/(n (N-1))), the code is as follows:
function Err=stderr (arr)
% experimental error (standard deviation estimate)
? Culate along each column of arr
ERR=STD (arr)./SQRT (Size (arr,1)-1);
File as STDERR.M, run-time input a=[1;2;3]; Create a column array A, and then enter stderr (a) to give the variance of a. (If the input row array is divergent, because N-1=0)
In this example, the input variable is arr, the function is named stderr, the output variable is err, and all three are written in the same row after the keyword function. You no longer need to return the value of err with return.
Note:
(1) The name of the function file is to be named with the main function declaration in the file, otherwise an error occurs. Within the
(2) function, you can nest a child function and call the main function of the file, just write the sub-function behind the main function code.
(3) A function can have more than one input and output. The M file in the function [Y1,y2]=myfun (X1,X2,X3)
Example 1 can insert a line before the first line:
function Randplt
after it is saved, the file becomes a non-input output volume.
It is generally more efficient to perform the same tasks in MATLAB using function files than script files.
3. Use of function handles
The function handle acts as a function pointer in the C language.
Example 3: Write a function to find the standard deviation (STD) and error (STDERR) of the array arr1 and ARR2.
Solution: Write the following file and save as ERREVAL.M
function [S1,s2]=erreval_r (ERR,ARR1,ARR2)
% err is the error function that is called, S1,S2 returns the error of ARR1 and ARR2 respectively.
S1=feval_r (ERR,ARR1);
S2=feval_r (ERR,ARR2);
The input to this file contains the function variable, which implements the assignment of the function variable err by a function handle.
The runtime first runs the following command to set up the array arr1,arr2:
ARR1=[1;2;3];
ARR2=[10;20;30];
And then enter
[Std1,std2]=erreval_r (@std, ARR1,ARR2)
[Stderr1,stderr2]=erreval_r (@stderr, ARR1,ARR2)
Returns four error values after execution.
@std, @stderr a function handle with two error functions.
Vii. Documents
Open File:
FID = fopen (filename,permission)
% of the permission is open type, specific to the MATLAB help document.
Read the file:
[A,count] = fread (fid,size,precision)
%A is the variable that holds the data read in.
%count is an optional parameter that holds the number of data read successfully.
%fid is a file pointer.
%size The amount of data that is required to be read, by default reading to the end of the file.
The%presision is read out in the data format.
Write file:
Count = fwrite (fid,a,precision)
Viii. visualization of data and functions
Fine-grained control of the image great article can do, here only some of the most common basic commands to make diagrams.
1. Visualization of two-dimensional data
Set X, y as a one-dimensional array of two equal lengths, to plot the elements of the x, y corresponding position, use the following command:
Plot (x, y);
If you use:
Plot (x);
is equivalent to:
S=size (x);
Plot (X,[1:s (2)]);
We can control the line and color, such as plot (x, Y, '. R ') to draw a red dot line.
The Linetype and color control values are shown in the following table:
Line symbol meaning
-Solid Line
: Dashed
-. Dot Dash
--Double Dash
Meaning of the color symbol
b Blue
G Green
R Red
C Green
M Magenta
Y Yellow
K-Black
W White
2. Visualization of three-dimensional data
PLOT3 is the easiest to understand:
PLOT3 (x, y, z);
The other two basic commands are:
Mesh (x, y, z)% to draw a network diagram.
Mesh (z)% The line graph is drawn with the z-matrix column row labeled X, Y axis arguments.
Surf (x, y, z)% draw a surface chart.
Surf (z)% plot a surface chart with Z-matrix column rows labeled x, y axis arguments.
3. Image control Commands
Figure% Open a new drawing window
Axis ([0,pi,-1,1])% control axis range
Title (' pic ')% Add caption to image
Grid on% display grid of coordinates
Legend% display Legend
Hold on% keep the previous picture when you draw the next picture.
Hold off% Stop the previous diagram.
Colorbar% Display Color bar
box on% Show box borders for three-dimensional graphs
% full text ends.
Basic usage of MATLAB