Part
Two
Lecture
❂ Command Line Editing
❂ Introductory Demonstration
❂ Help
❂ Simple Matrix Input
❂ Statements and Variables
❂ Data Structures: Vectors, Matrices, Struct Arrays, and Cell Arrays
❂ Mathematical Operations and Functions
❂ Plotting Commands
① There are two common forms of MATLAB statementsi) Expression ii) variable = expression Example 1: Calculation of an expression 1996/18 ↵ans=110.8889 Example 2: Assigning the result of a calculation s=1-1/2+1/3-1/4+1/5-1/6+…1/7-1/8; ↵Note: The three dots are “line continuation”, the semicolon “;” means that the result of the command will not be displayed on the screen, but the variable s will reside in memory. If the user wants to see the value of s, they can type the following command: s ↵(s=0.6345) ② Special Variables ans is the default variable name for results pi is the value of pi eps is the smallest number the computer can represent flops is the number of floating point operations inf represents infinity like 1/0 NaN represents an undefined quantity like 0/0nargin is the number of input variables for the function nargout is the number of output variables for the function realmin is the smallest positive real number realmax is the largest positive real number
① Conjugate Transpose of a Vectorz=[1+j,2+pi*i,-sqrt(-1)]’z =1.0000 – 1.0000i 2.0000 – 3.1416i 0 + 1.0000i Get its conjugate transpose vector. z.’ (non-conjugate transpose vector)
② Generate a Row Vectort=[0:0.1:10] % Generate a row vector from 0 to 10 with an interval of 0.1 t=linspace(n1,n2,n) % Generate n numbers uniformly distributed between n1 and n2 (default n generates 100 numbers) t=logspace(n1,n2,n) (default n generates 50 points) ③ who, whos, size, and length are four commands that are very useful for providing information about workspace variables. who lists all the variables in the workspace; whos displays all variables, the number of elements in each variable, and the number of bytes used; size(a) returns the number of rows and columns of matrix a; length(a) returns the length of vector a. If a is a matrix, the displayed parameter is the maximum of the number of rows and columns. ④ Matrix Indexing A(m,n) refers to the element in the m-th row and n-th column of matrix A; A(1:2,1:3) refers to all elements from the first to the second row and from the first to the third column of matrix A; A(:) gives a long vector with the elements stacked column-wise. For example, a=[1 2;3 4]; a(:) ↵ans=1324 Matrix indices can also be vectors. For example, b=a(x,y) ↵; can yield a matrix b. The row indices of a come from vector x, and the column indices come from vector y. For instance, if matrix a has n columns, then b=a(:,n:-1:1) will yield matrix b, which is the reverse of matrix a column-wise. ⑤ Special Matrices i) Identity matrix eye(m), eye(size(a)) can generate an identity matrix of the same size as matrix a, eye(m,n) generates the largest allowable identity matrix with the rest filled with 0. ii) Matrix with all elements as 1 ones(n), ones(size(a)), ones(m,n) iii) Matrix with all elements as 0 zeros(n), zeros(m,n) iv) An empty matrix is a special matrix that does not exist in linear algebra. For example: q=[ ] Matrix q exists in the workspace, but its size is zero. An empty matrix can be used to delete rows and columns. For example, a=rand(5); a(:,1:3)=[] The first command generates a 5×5 matrix; the second command deletes the first three columns of matrix a. v) Diagonal matrix when v is a vector, diag(v) generates a diagonal matrix with the elements of v on the diagonal; when v is a matrix, diag(v) returns a column vector containing the elements on the diagonal of matrix v, diag(v,1) returns the elements on the diagonal of matrix v shifted up by one row, diag(v,-1) returns the elements on the diagonal of matrix v shifted down by one row.
⑥ Strings must be enclosed in single quotes.For example: disp(‘text string’) % disp is a display command and there are several string commands that can be used as text descriptions and plot titles, such as num2str, int2str, fprintf, and sprintf. Similarly, the help command can be used to understand their specific usage. ⑦ Struct Arrays Sometimes it is necessary to combine different data types into a whole for easier reference. These data combined into one whole are interrelated. For example, a student’s ID number, name, gender, age, grades, home address, etc., are all related to that student. Below is a brief introduction to the definition and referencing of structs. i) Struct arrays can be defined in two ways: by assignment statements and using the struct function. When defining a struct by assignment, simply assign values to the properties, and MATLAB will automatically add that property to the struct. When assigning, the struct name and property name are separated by a “.”. For example, the following three statements define a 1×1 struct array named student with three properties: name, num, test. The struct array has only one element, and typing the struct name student in the command window will display the values of all properties of that element. student.name=’John Doe’; student.num=123456; student.test=[79 75 73;80 78 79;90 85 80]; Typing the following three lines will add an element to the struct array. student(2).name=’Ann Lane’; student(2).num=123422; student(2).test=[70 76 73;80 99 79;90 85 80;80 85 86]; Now the struct array student has dimensions of 1×2.When the number of elements in the struct array exceeds 1, MATLAB’s display information will no longer show the values of different properties but will only display the array name, property name, and dimension size. The struct function can also be used to define struct arrays, with the calling format: struct array name = struct(‘Property 1’,‘Property Value 1‘,‘Property 2‘,‘Property Value 2‘,…)ii) Modifying, setting, and accessing property values of struct arrays Once a struct array is formed, it is possible to retrieve a specific element from the array and modify the value of a certain property of that element. For example, using the previously established student array, the command str=student(2).name retrieves the name property value of the second element. The command n=student(2).test(4,2) retrieves the value in the test of the second element at the fourth row and second column. Similarly, the command student(2).test(4,2)=0 modifies the value in the test of the second element at the fourth row and second column.
⑧ Cell ArraysCell arrays are also a special type of array in MATLAB. Due to the existence of cell arrays, it is possible to group arrays of different types and dimensions into one array. Each element of a cell array can be a matrix, vector, scalar, or multidimensional array of different types and dimensions, all enclosed in curly braces. For example, matrix A=[1 2 3 4;2 3 4 5;3 4 5 6], the command c={A,sum(A),sum(sum(A))} generates a 1×3 cell array.
i) There are two methods to generate cell arrays: directly generating them with assignment statements; or preallocating the array using the cell function and then assigning values to each element. Two methods can be used to assign values to the elements: one method uses the array element’s index for assignment. The following four commands will create a 2×2 cell array. A(1,1)={[1:5;6:10]}; A(1,2)={‘Anne cat’}; A(2,1)={3+7i}; A(2,2)={0:pi/10:pi}; In curly braces, a comma or space indicates separation between elements in the same row, while a semicolon indicates separation between different rows. Another method uses curly braces to index the cell array, while assigning values in the form of regular arrays. For example, the four commands generated in this way are identical to those above. A{1,1}=[1:5;6:10]; A{1,2}=’Anne cat’; A{2,1}=3+7i; A{2,2}=0:pi/10:pi; The command B=cell(3,4) creates a 3×4 cell matrix. ii) To view the contents of the above-created array A, typing the variable name A in the MATLAB command window will display a brief overview of the array. Using curly braces { } for indexing indicates which element of the cell array, while using parentheses () indicates the component of that element corresponding to the curly braces { }. For example, A{2,2}(1), A{4}(1) will display the same result for the above cell array. The function celldisp is used to display the values of each element in the cell array. The function cellplot will draw the structure of each element in the cell array. When assigning values to elements outside the defined index range of an already defined cell array, MATLAB automatically expands the dimensions, and unassigned elements are assigned as empty matrices.
PS. This article is copyrighted by Teacher Si Ma Kui from the Naval Aviation Engineering Institute
Journal of Nanjing University of Information Science and Technology