Matlab learning notes 2: basic knowledge of MATLAB (middle)

Posted by lakshmiyb on Thu, 10 Feb 2022 11:05:43 +0100

Please note before reading:

1. This learning note is the learning record of MATLAB training of HelloWorld programming Association of central China Normal University in 2021 winter vacation. It is a summary and expanded reading based on the training classroom content. The content of the blog is written and edited by @ K2SO4 potassium and published in the personal contribution of @ K2SO4 potassium and the official account of CSDN of HelloWorld programming Association of central China Normal University @ CCNU_HelloWorld . Note that if you need to reprint, you need the consent and authorization of the author @ K2SO4 potassium!

2. The learning notes are based on MATLAB R2018a complete self-study and one pass (Liu Hao, Han Jing) 1 , many program examples and the author's personal thinking are added to the notes. Learning notes are for novices who have just come into contact with MATLAB, and the content is basic. The example in the notes is MATLAB R2019a.

3. Please understand the possible errors in the notes and welcome correction and discussion; If the old code cannot be used due to MATLAB update, you are also welcome to discuss and exchange.


2.0 MATLAB learning notes: portal summary


2.0.1 MATLAB learning notes: portal summary


MATLAB learning notes 0: learning instructions

Matlab learning notes 1: overview of MATLAB

Matlab learning notes 2: basic knowledge of MATLAB (I)

Matlab learning notes 3: Fundamentals of MATLAB programming (first half)

Matlab learning notes 3: Fundamentals of MATLAB programming (second half)


2.0.2 MATLAB extended learning: portal summary


MATLAB extended learning T1: anonymous functions and inline functions

MATLAB extended learning T2: program performance optimization technology

MATLAB extended learning T3: detailed explanation of histogram function

MATLAB extended learning T4: data import and table lookup Technology

Content under construction~~


Matlab portal: in depth learning 2.0


In depth study of MATLAB S1: matlab implementation of digital filtering technology

Deeply study S2: cellular automata principle and matlab implementation in MATLAB

MATLAB in-depth study S3: image processing technology

Content under construction~~


2.0.4 MATLAB application example: portal summary


MATLAB application example Y1: Floyd algorithm

Content under construction~~





2.1 data type


2.1.4 character array type (char) and string array type (string)


MATLAB generally uses character array type and string array type for string storage, of which the former is more commonly used.

In MATLAB, strings can be displayed on the screen, or used for some specific operations, or used to form some commands. A string can be regarded as a line vector in MATLAB. Each element in the line vector stores ASCII code to represent a corresponding character. When the string is displayed in the command line window, it is also displayed in the form of characters, not ASCII code.

Matlab can have Chinese characters in the string, so using the character array type to represent a character needs 2 bytes (16bit) (if it is Chinese, it needs 2byte storage space for representation, if it is only English symbols, it only needs 1byte, i.e. ASCII code. MATLAB is compatible with Chinese, so it uses the storage size of one character 2byte). Using the whos function mentioned in the first chapter can quickly check the space occupied by the string, and using the abs function can also check the ASCII code of each character in the string.

Use single quotes to quickly create an array of characters.

clc, clear all, close all
str = 'abc I'
whos
abs(str) % View each element of the string ASCII code


In the above example, the string s t r str str uses a 1 ∗ 4 1*4 1 * 4 character line vector representation.

Because ASCII code is saved in the character array, if the character array is directly calculated, the result will be expressed in the matrix of ASCII code. Then use the char function (setstr function in the old version) to convert ASCII code into character array.

clc, clear all, close all
str1 = 'abc I'
str2 = str1+3 % This is actually a double Type of matrix, recording ASCII code
str3 = char(str2)



Since the character array itself is a matrix, many operations are the same as the matrix. Common operations for strings are described below.


2.1.4.1 character array extraction and merging


Similar to the operations of extracting the elements in the matrix and merging the two matrices, colon is used when extracting: the elements in the character array are extracted, and brackets [] are used when merging the two character arrays. Note that if two character arrays have different lengths (i.e. dimensions), they can only be merged into a new row vector, not a character matrix.

The inversion of character array is similar to the extraction of character array, as shown in the following example.

clc, clear all, close all
str1 = 'MATLAB';
str2 = 'yyds';
str3 = '_yyds_';
ans1 = str1(4:6) % extract str1 Medium'LAB',It can also be written as str(4:1:6)
ans2 = [str1,str2] % merge str1,str2 For the new row vector
try
    ans3 = [str1;str2] % An error is reported because the matrix dimensions are different
catch
    ans4 = [str1;str3]
end
ans5 = str1(6:-1:1) % Inverted, equivalent to from str1 Starting from the 6th bit, take one bit forward each time until the 1st bit
ans6 = str1(1:2:6) % yes str1 Take one every other character



2.1.4.2 character array takes ASCII code and ASCII code recovery character array


As mentioned above, it will not be repeated here. Use the abs function to get the ASCII code of the character array, and use the char or setstr function (old version) to recover the character array from the ASCII code.


2.1.4.3 comparison of character arrays


To compare whether two character arrays are the same, there are usually the following functions:


In addition to the character array comparison function, you can also use relational operators to compare whether each character of two character arrays is the same one by one. It should be noted that this comparison method requires two character arrays with the same length (i.e. the same dimension). During comparison, ASCII code is used for comparison, and the returned result is logical true (1) or logical false (0).

clc,clear all,close all;
str1 = 'snack';
str2 = 'snake';
ans1 = str1 == str2 % take str1 == str2 The result of the operation is assigned to ans1
ans2 = str1 > str2



2.1.4.4 search and replacement of character array


For the search of character array, there are usually the following functions:

findstr(str1, str2) (old version): find the position where the shorter character array in str1 and str2 appears in the longer character array, that is, find another shorter character array in a longer character array. If there are multiple positions, the row vector of the position is returned. If there is no search, the empty matrix is returned.

strfind(str1, str2): find the position where str2 appears in str1, that is, find another shorter character array in a longer character array. If there are multiple positions, the row vector of the position is returned. If there is no search, the empty matrix is returned.

[row, col] = find(expr): this function returns the index of elements in the matrix that match the expr expression, that is, the subscripts of all matrices that match the expression. For various types of matrices (including character arrays), it is very efficient to use the find function for retrieval.

For replacement of character array:

strrep(str1, str2, str3): replace the character array str2 contained in the character array str1 with the character array str3.

clc, clear all, close all
str1 = 'Welcome to CCNU HelloWorld !';
str2 = 'CCNU';
ans1 = findstr(str2,str1)
ans2 = strfind(str1,str2)
ans3 = find(str1(1,:)=='o') % return str1 The element value in the first line is'o'Column of
ans4 = strrep(str1,str2,'Central China Normal University')


2.1.4.5 execute the MATLAB expression in the text


When the character array contains executable MATLAB expressions, the eval function can be used for execution.

clc, clear all, close all
a = pi/3;
str = 'sin(a)+cos(a)'
eval(str)



2.1.4.6 numeric conversion function of character array


Common functions are as follows:


2.1.4.7 introduction to string array and printing of string


String array, as the name suggests, is that each element in the array is a string. Use double quotation marks to create a 1 ∗ 1 1*1 1 * 1 Size string array (i.e. string type), also known as string scalar. You can also use the string function to create a string type, or create a string type through brackets [] and double quotes "".

The fprint function can only print string scalars in the command line window, while the disp function can print string arrays in the command line window.

clc, clear all, close all
str1 = "abc"
str2 = string('abc')
str3 = ["wjn","dyz","zwt","pym","wx"]
fprintf(str1)
disp(str3)
whos

In the basic learning stage, the application of string array is much narrower than that of character array, and the number of functions operating string array is limited. Therefore, the string array is just a brief introduction. For specific application, please refer to the help document.


2.1.4.8 other functions related to string (understand)



For more string functions, refer to the help documentation.



2.1.5 structure type (struct)


Structure refers to a data set composed of a series of data of the same type or different types, that is, a data type that uses a data container named field to combine relevant data together.

The members in the structure can be any data type (even a structure type, but the nested structure needs to be built in advance). Access the member usage point of the structure (dot) to access, such as stu_ major in sys, using stu_sys.major to access. The same is true for the creation of structures (of course, you can also use the struct function), without declaration.

Use rmfield(s,field) to delete fields in the structure.

clc,clear all,close all;
TIME1.h = 8;
TIME1.m =30;
TIME2.h = 10;
TIME2.m =30;
stu_sys.student_name = 'dyz';
stu_sys.student_ID = 20190001;
stu_sys.major = 'physics';
stu_sys.final_score = 92;
stu_sys.exam_start = TIME1;
stu_sys.exam_end = TIME2;

stu_sys
fprintf('\n structural morphology stu_sys Information about:\n')
whos
fprintf('The student's major is:%s', stu_sys.major)



Using struct function combined with cell array can quickly create structure array.

clc,clear all,close all;
s = struct('type',{'big','little'},'color','red','x',{3 4})
s(1).type

The above code produces a 1 ∗ 2 1*2 Structure array of 1 * 2. To access the elements, you need to specify the number of elements in the structure array.



————↓ ----- prompt ----------- ↓————

When using the structure in MATLAB, it is more efficient and convenient to directly use the point method. When using struct function to build a structure, you should first know its calling method:

S = struct('content 1 ', value 1,' content 2 ', value 2,...)

--↑-----—↑--



2.1.6 function handle


In MATLAB, there are two ways to call a function: direct call and indirect call.

Direct call mode, that is, call a stored in M file, function with the same name as the file name. The location of the m file where the function is stored is the path that MATLAB looks for when searching the function. For example, call the sin function, and MATLAB will search for sin in the working path M file and call the sin function in the file.

Indirect call mode, that is, the input parameters, output parameters and data processing expressions of a function are represented by a function handle. The path of this function handle is the same as that of the code segment where the function handle is stored The storage paths of m script files are consistent, so users do not need to consider the call location when creating. Users can create some simple functions through the function handle without using the function function function to establish functions at the end of the code segment or in other function files.

Function handle can reduce code redundancy and facilitate users to write programs; It is convenient for functions to call each other and improve the efficiency of repeatedly executing code; Improve the reliability and compatibility of function calls. But it also has obvious disadvantages, that is, it can not represent functions with more complex functions, especially when it comes to loop body and calling complex functions.

An anonymous function is a function handle.

There are three ways to set a function handle.

The first way is to use the @ symbol to create:

Set a function handle (pseudo code)
Function name = @ (input parameter 1, input parameter 2,...) expression

The second way is to use the str2ffunc function to convert the string into a function handle:

Set a function handle (pseudo code)
%The first way
Function name = str2ffunc ('@ (input parameter 1, input parameter 2,...) expression')
%The second way: in the future version, this way of writing will report an error
Function name = str2ffunc ('expression ')

The third way is to use symbolic expression and then use matlabFunction function to convert it into function handle:

Set a function handle (pseudo code)
syms input parameter 1 input parameter 2
Function name = Matlabfunction (symbolic expression)

The way to call a function handle is as follows:

Call a function handle (pseudo code)
Output parameter = function name (input parameter 1, input parameter 2,...)


clc,clear all,close all
%% The first setting method
func1 = @(x,y) sin(x).*cos(y)
ans1 = func1(pi/2,0)
%% The second setting method
func2 = str2func('@(x,y,z) x+y+z')
ans2 = func2(1,2,3)
%% Third setting method
syms x y;
a = 1; b = 2;
func3 = matlabFunction(a*x+b*y)
ans3 = func3(1,1)


The construction of function handle can also refer to existing functions. For example, if you want to reference the exp function, you can use:

New function name = @ existing function name

clc,clear all,close all
fh = @exp;
fh(3)



For specific applications of function handles (nesting, representing piecewise functions, etc.), the use of inline functions and anonymous functions, please refer to: MATLAB extended learning T1: anonymous functions and inline functions.



2.1.7 cell matrix


Cell matrix, also known as cell array and cell array, is a generalized matrix. The elements in the cell matrix can be of any data type (therefore, you can also "Dolly" the cell matrix), and the = = Size (Size) and storage space (Bytes) = = of each element can vary according to the data type of the storage element. Like ordinary matrices, cell matrices can be multidimensional matrices, and can also be merged, extracted and deleted (see Section 2.3 for the operation of ordinary matrices).

There are two ways to create a cell matrix: using the cell function and using braces' {} '.

clc,clear all,close all
A = cell(3,2) % Create a 3*2 Empty cell array
B = {'abc',uint(2);logical(0),3+2*1i} % Create an assigned 2*2 Cell array



MATLAB provides two operations for the cell matrix: searching the cell matrix (Cell Indexing) and searching the elements in the cell matrix (Content Addressing). The symbols and functions of the two operations are different, so special attention should be paid to distinguish them when using them.

Use parentheses' () 'to find the cell matrix. For example, A(m,n) operation is performed on cell matrix A, that is, the cells in row m and column n of cell matrix A are extracted to obtain a 1 ∗ 1 1*1 1 * 1 cell type; Use braces' {} 'to find elements in the cell matrix. For example, A{m,n} operation is performed on cell matrix A, that is, the elements in row m and column n of cell matrix A are extracted, and the data type of the elements in the corresponding cell is obtained.

Braces are required when assigning values to a cell matrix and deleting elements of a cell in the cell matrix; The combination of the cell matrix requires the use of square brackets (the use of braces will form the nesting of the cell matrix); When extracting and deleting a cell matrix, you need to use parentheses.


clc,clear all,close all
A = {"abab";5.4};
B = {'abc',uint(2);logical(0),3+2*1i};
%% Search for element matrix and element of element matrix
ans1 = B(2,2) % Search for the element matrix (extract the element matrix) to obtain cell type
ans2 = B{2,2} % Search for element matrix elements (extract elements) to obtain complex type
%% Assign a value to the element of the cell in the cell matrix
% A(1,1) = 2; % Will report an error: unable to double Convert to cell
A{1,1} = 2;
ans3 = A
%% Combined element matrix A,B
ans4 = [A,B]
%% Delete cell matrix B Second line of
B(2,:) = [];
ans5 = B
%% Continue deleting cell matrix B Elements in row 1 and column 2
B{1,2} = [];
ans6 = B



Understand container (Map. 2)


2.1.8.1 introduction to map container (understand)


Map container, also known as map mapping table, is a high-level data type used to linearly map one quantity to another.

Each key in the container can't have the same value as a set of keys. The linear mapping property of map container is similar to that of function. For a function, each independent variable is unique and has a unique dependent variable value corresponding to it. Conversely, this relationship does not hold. The map container is similar to it. Each key is unique and has a unique value corresponding to it. The reverse is not true.



Therefore, the keys in the map container must be of the same data type and one of the following three data types: numeric array, character vector cell array and string array; The value corresponding to each key can be different data types, which only needs to correspond to the key one by one.

The following table shows the data types allowed by KeyType:



2.1.8.2 advantages of map container (understand)


As a high-level data structure for fast search, map container has the advantages that other data structures do not have. 2

There are many instances of map containers in life. For example, in the "student number name" pair in the school, the student number is unique, so as a "key", each student number has its corresponding name. The name and name can be the same, so the name is used as a "value".

Considering the above "student number name", if we use the cell array storage mentioned before, it is obvious that the one-to-one mapping relationship between student number and name cannot be shown. If you want to find the value corresponding to a key, you need to find the column subscript of the key in the cell array corresponding to the key, and then find the value corresponding to the key in the cell array corresponding to the value according to this subscript. Because you need to traverse the cell array, this process will consume more time.

Secondly, the cell array of keys cannot limit each key to be unique, and there is no guarantee that the new key is different from the existing key when adding a new 'key value' pair.

In addition, when deleting a 'key value' pair, modifying the value corresponding to a key, and displaying the value corresponding to some key, we will also encounter the same problem, that is, the one-to-one correspondence between the key and the value cannot be reflected, so we can only traverse the key to find its subscript, use its subscript, and then change the content of the corresponding value, which is time-consuming.

Finally, when adding a new 'key value' pair, if the added content exceeds the preset cell array size, MATLAB will reallocate memory, unable to dynamically allocate memory, and the code performance will be further degraded.

clc,clear all,close all
% Primary key-Value pair
fprintf('Primary key-Value pair\n')
stu_ID = {201901,201801,202001,201902,201903} % key
stu_name = {'dyz','wjn','lyx','zwt','pym'} % value
% New key-Value pair
fprintf('New key-Value pair\n')
stu_ID{end+1} = 2019 % Reassign and reduce performance
stu_name{end+1} = 'wx'
% Delete key-Value pair 201801-'wjn'
fprintf('Delete key-Value pair 201801-wjn\n')
for i = 1:length(stu_ID) % Traversal to reduce performance
    if stu_ID{1,i} == 201801
        index = i;
        stu_ID(index) = [];
        stu_name(index) = [];
        stu_ID
        stu_name
        break
    end
end



Considering the one-to-one mapping relationship, we can also think of a data type we have learned: structure. If you use the previously learned structure to replace the map container, it has certain advantages over expressing the cell array: it can express such a mapping relationship, so it has advantages over the cell array in the modification, deletion and query of 'key value' pairs. However, like cell arrays, they still have the disadvantage of not making keys unique.

Another disadvantage is that if the key is a numeric type, the structure cannot be stored (because the naming of variables is limited). Only when the key is a character array type can you replace the map container with a structure type. In this way, the structure of the relationship like 'student number name' above will not be able to express.

Another disadvantage is that when we need to store a large number of 'key value' pairs, using the structure type to store makes the code too lengthy.

Insert code slice here clc,clear all,close all
% plane ticket ID-Passengers
% Primary key-Value pair
T_P.AM704 = 'dyz';
T_P.CT497 = 'wjn';
T_P.SG627 = 'lyx';
fprintf('Primary key-Value pair\n')
T_P
% Add key-Value pair
T_P.MS562 = 'pym';
fprintf('Add key-Value pair\n')
T_P
% Delete key-Value pair
T_P = rmfield(T_P,'CT497');
fprintf('Delete key-Value pair\n')
T_P
% Query key-Value pair
fprintf('query AM704 Value of\n')
T_P.AM704



To sum up, the map container has the following advantages over other data types:

  1. It can reflect the one-to-one correspondence between 'key value' and ensure the uniqueness of the key;
  2. It can quickly find the value corresponding to the key and quickly display all 'key value' pairs. There are counts for 'key value' pairs. The search complexity is O(1), while the search complexity using traversal method is O(n);
  3. When adding a new 'key value' pair, the space will not be reallocated and no pre allocation is required;
  4. There are special functions for modifying the corresponding value of the key and removing the 'key value' pair, which is very convenient for the operation of the map container;



2.1.8.3 creation of map container (understand)


MATLAB through containers The map function creates a map container and its mapping relationship. The calling method is:

containers.Map(keySet, valueSet): create a map object containing keys from the keySet. Each key is mapped to a corresponding value in the valueSet. They should have the same number of elements, and each key in the keySet must be unique;

containers.Map('KeyType ', specify the data type of key,' ValueType ', specify the data type of value): create an empty map object and specify the data type of key and value that can be added to it later.

There are three basic attributes of the map: Count (record the total number of key value pairs in the map container), KeyType (record the data type of the key in the map container), ValueType (record the data type of the value in the map container, if there are multiple data types, record 'any'). Map also has an attribute called 'UniformValues', which defaults to false and specifies whether the ValueType needs to be unified. If you need to unify the types of values, you can set 'UniformValues' to true.

clc,clear all,close all
% Key is a numeric array( double),The value is a character array( char)
cm1 = containers.Map([2020 2021 2022 2023 2024],{'rat','cattle','tiger','rabbit','Loong'})
% Cell array with key as character vector( char),The value is of any data type( any)
cm2 = containers.Map({'A201901','C201802','D201803','Counter'},{'dyz','wjn','hhq',3})
% Key is a string array( char),Values are numeric arrays( double)
keySet = ["MU5260","MU7004","MU6062"];
valueSet = [46 60 58];
cm3 = containers.Map(keySet,valueSet)



2.1.8.4 retrieval of map container (understanding)


For a map container, enter the key to quickly retrieve its corresponding value. Here are three methods to retrieve the corresponding value of the key in the container:

To retrieve the value of a single key:

Corresponding value = map container name (key)

Retrieve the values of multiple keys: use the values function

Corresponding value = values(map, container name, key)

Retrieve all keys and corresponding values in a map container: keys function and values function

Key = keys(map container name)
Corresponding value = values(map container name)
(the two correspond one by one)

clc,clear all,close all
cm1 = containers.Map([2020 2021 2022 2023 2024],{'rat','cattle','tiger','rabbit','Loong'});
cm2 = containers.Map({'A201901','C201802','D201803','Counter'},{'dyz','wjn','hhq',3});
cm3 = containers.Map(["MU5260","MU7004","MU6062"],[46 60 58],'UniformValues',true);
result1 = cm1(2022)
result2 = values(cm2,{'A201901','C201802','D201803'})
result3_keys = keys(cm3)
result3_values = values(cm3)



2.1.8.5 operation of map container (understand)


Remove key value pairs


Use the remove function to remove the 'key value' pair in the map container. The call method is:

remove(map container name, key to be removed)

clc,clear all,close all
TicketNum = {'A204','F40K','7U99','D1A4','XH7A','S47A'};
Passengers = {'dyz','wjn','pym','lyx','wx','zwt'};
cm = containers.Map(TicketNum,Passengers);
fprintf('map container cm: \n')
keys(cm)
values(cm)
% Remove key'XH7A','S47A'
removed_cm = remove(cm,{'XH7A','S47A'});
fprintf('map container removed_cm: \n')
keys(removed_cm)
values(removed_cm)


Add 'key value' pair


Existing map container name (new key name) = corresponding value: add a 'key value' pair.

clc,clear all,close all
TicketNum = {'A204','F40K','7U99','D1A4','XH7A','S47A'};
Passengers = {'dyz','wjn','pym','lyx','wx','zwt'};
cm = containers.Map(TicketNum,Passengers);
fprintf('map container cm: \n')
keys(cm)
values(cm)
% New key'CM6A','DM4D'
cm('CM6A') = 'xzh';
cm('DM4D') = 'hhq';
added_cm = cm;
fprintf('map container added_cm: \n')
keys(added_cm)
values(added_cm)


Modify key


To modify the key name, you need to remove the original key first, and then add the corrected key and its corresponding value.

clc,clear all,close all
TicketNum = {'A204','F40K','7U99','D1A4','XH7A','S47A'};
Passengers = {'dyz','wjn','pym','lyx','wx','zwt'};
cm = containers.Map(TicketNum,Passengers);
fprintf('map container cm: \n')
keys(cm)
values(cm)
% Modify key'A204'by'A256'
remove(cm,'A204'); % remove'A204'
cm('A256') = 'dyz'; % increase'A256'
modified_cm = cm;
fprintf('map container modified_cm: \n')
keys(modified_cm)
values(modified_cm)



Value corresponding to modification key


Modifying the value corresponding to a key is the same as adding a key value pair.

Existing map container name (existing key name) = new corresponding value

clc,clear all,close all
TicketNum = {'A204','F40K','7U99','D1A4','XH7A','S47A'};
Passengers = {'dyz','wjn','pym','lyx','wx','zwt'};
cm = containers.Map(TicketNum,Passengers);
fprintf('map container cm: \n')
keys(cm)
values(cm)
% Modify key'D1A4'Medium'lyx'by'hhq'
cm('D1A4') = 'hhq';
modified_cm = cm;
fprintf('map container modified_cm: \n')
keys(modified_cm)
values(modified_cm)



2.1.9 table (understand)


In our life, we will always encounter one form or another, such as the daily temperature clock in a grade winter vacation, or the information form of all employees in a department in the unit. When dealing with data, we are also dealing with tables. We extract the original data from the tables, and then analyze and interpret the data. When you think about it, a lot of data around us can be stored in tables. Because tabular data is more and more widely used in engineering calculation, table type is designed in MATLAB.

In addition, we also mentioned in the previous section that basic data types, such as cell arrays and structures, will have more or less defects (such defects are mainly due to the fact that the data cannot be stored and the operation is more troublesome). Therefore, data types such as table and map containers will be more widely used.

Use the table function to create a table:

table(var1, var2,..., 'VariableNames',' var1_name ',' var2_name ',...}): VAR1, var2,..., varn are column vectors of equal length. As columns 1, 2,..., and n of the table, these columns are named' VAR1 'respectively_ name’, ‘var2_ name’, …

For example, use MATLAB to create the following table:


Such a table can be imported directly through the importdata function, xlsread function or csvread function, but it is not within the scope of our discussion in this section. Use the table function to create a table:

clc,clear all,close all
FDN = {'New Energy';'Ordinary Cola';'Medical Apparatus';'Dairy Produce';'Driverless'};
FC = {'0001';'0002';'0003';'0004';'0005'};
C = {'DEV-ENERGY Inc';'SNG-Food Inc';'CS-Med Inc';'SNG-Food Inc';'Tex-Tech Inc';};
IN = [1.432;-0.661;2.386;0.254;3.046];
Class = uint16([3;1;6;1;2]);
My_Table = table(FDN,FC,C,IN,Class,'VariableNames', ...
    {'Funds_Descriptive_Name','Funds_Code','Company','Fluctuation_Range','Class'})


Careful students may find that when naming each column of the table, the author did not use the strings such as' Fund's Descriptive Name 'in the original table, but used' funds'_ Descriptive_ Name ', etc. This is because the column name and table name should comply with the variable naming specification of MATLAB. Through isvarname(var), you can quickly check whether the variable name is a legal variable name.

For the data type of table, MATLAB has three ways to access the elements:


(1) Use parentheses' () 'to return the type of table


Use the table name (row range, column range) to access, and the results will form a new table for returning the contents of the corresponding range in the table. Take the table above as an example:

% In the table above 'My_Table' take as an example
My_Table(2:4,2:3) % visit My_Table Of 2-4 OK, 2-3 column



(2) Use braces' {} 'to return the data type of the selected content


It should be noted that since the data type of the selected content is returned when using braces, an error may occur when the data type of the selected content is different (that is, it cannot be concatenated into a result matrix).

% In the table above 'My_Table' take as an example
result1 = My_Table{1:3,1:2} % Due to the cell array used during creation, the cell array containing the string will also be returned here
result2 = My_Table{1:4,4} % return double type
result3 = My_Table{1:3,4:5} % Because the fourth column is double,The fifth column is uint16,
                            % The combination of the two will form 3*2 of uint16 Matrix( double The type is forced to uint16 (type)
% result4 = My_Table{1:3,3:4} % An error will be reported because the selected content has double Again cell(cell Contains a string), MATLAB It cannot be merged into one matrix



(3) Use dot and parentheses


Use table name Column name (row range) or table name The column name {row range} (the latter is not supported for numeric data). The former returns the data type of the selected content, and the latter returns each element of the selected content.

% In the above text 'My_Table' take as an example
result1 = My_Table.Funds_Descriptive_Name(3:5) % Return 3*1 of cell Type( cell (contains string)
result2 = My_Table.Funds_Descriptive_Name{3:5} % Returns three results, each of which is of string type
result3 = My_Table.Fluctuation_Range(3:5) % Return 3*1 of double type
% result4 = My_Table.Fluctuation_Range{3,5} % An error will be reported because the selected content does not support the use of curly braces for indexing



Using a data type such as table can process the data in it more quickly and conveniently. The following example.


☆ example 2-9: (understand) the 20 day sales of a overtime fruit area is exported from the database as follows. Complete the task as required.


(1) According to the table content, use the table data type to store the data in MATLAB;

(2) Calculate the total selling price of these three fruits within 20 days, excluding the purchase cost and other costs;

(3) Draw the change curve of daily sales of three kinds of fruits in the same graph (using plot function);

(4) Find the maximum, average and median number of apples sold within 20 days.


analysis:

clc,clear all,close all

%(1)According to the contents of the table, use table Data type stores data in MATLAB;
apple = [32;41;55;71;90;84;76;73;70;66;65;63;61;77;109;122;127;103;109;118];
banana = [181;186;146;186;172;144;154;167;188;189;148;189;188;164;180;147;161;186;180;188];
tomato = [423;436;437;395;342;319;314;323;382;444;444;445;446;420;373;363;321;419;438;444];
date = {'2.04';'2.05';'2.06';'2.07';'2.08';'2.09';'2.10';'2.11';'2.12';'2.13';'2.14';'2.15';'2.16';'2.17';'2.18';'2.19';'2.20';'2.21';'2.22';'2.23'};
apple_unitprice = [1.58000000000000;1.52000000000000;1.97000000000000;2;1.29000000000000;1.64000000000000;1.59000000000000;1.83000000000000;1.90000000000000;1.96000000000000;1.39000000000000;1.87000000000000;1.84000000000000;1.26000000000000;1.21000000000000;1.65000000000000;2.20000000000000;1.47000000000000;1.76000000000000;1.33000000000000];
banana_unitprice = [1.56000000000000;0.980000000000000;1.27000000000000;1.50000000000000;1.73000000000000;1.81000000000000;1.32000000000000;0.840000000000000;0.850000000000000;0.980000000000000;1.67000000000000;0.980000000000000;1.64000000000000;0.960000000000000;1.77000000000000;1.09000000000000;0.910000000000000;0.970000000000000;1.40000000000000;1.23000000000000];
tomato_unitprice = [0.920000000000000;1.40000000000000;1.15000000000000;1.12000000000000;1.48000000000000;0.860000000000000;1.32000000000000;1.32000000000000;0.950000000000000;1.14000000000000;0.650000000000000;0.630000000000000;1.10000000000000;1.35000000000000;1.50000000000000;0.700000000000000;1.14000000000000;1.04000000000000;0.590000000000000;0.910000000000000];
My_Table = table(date,apple,banana,tomato,apple_unitprice,banana_unitprice,tomato_unitprice,'VariableNames', ...
    {'date','apple','banana','tomato','apple_unitprice','banana_unitprice','tomato_unitprice'})

%(2)Calculate the total selling price of these three fruits within 20 days, excluding the purchase cost and other costs;
Total_Sales = sum(My_Table.apple.*My_Table.apple_unitprice)+ ...
    sum(My_Table.banana.*My_Table.banana_unitprice)+ ...
    sum(My_Table.tomato.*My_Table.tomato_unitprice)

%(3)Draw the change curve of daily sales of three kinds of fruits in the same chart (use plot Function);
figure(1)
h = plot(1:20,(My_Table.apple.*My_Table.apple_unitprice)');
h.LineWidth = 2;
h.Color = 'r';
grid on
hold on
h = plot(1:20,(My_Table.banana.*My_Table.banana_unitprice)');
h.LineWidth = 2;
h.Color = 'g';
hold on
h = plot(1:20,(My_Table.tomato.*My_Table.tomato_unitprice)');
h.LineWidth = 2;
h.Color = 'b';
xlabel = 'date';
ylabel = 'sales';
legend('Apple','Banana','Tomato');

%(4)Find the maximum, average and median number of apples sold within 20 days.
apple_max = max(My_Table.apple)
apple_avg = mean(My_Table.apple)
apple_median = median(My_Table.apple)




Thinking question 2


☆ question 2-7: "all the wise for himself, a cool all for others." Is a classic English saying, translated as "a wise man asks for himself in everything, and a fool asks for others in everything". This famous English saying is stored in the variable standard as a character array. Given the string str1-str5, these five strings can be combined into the string standard, but there are problems in each of them. Complete the task as required.

standard = 'All the wise for himself, a fool all for others.';
str1 = 'all the wise ';
str2 = 'for flesmih, a '
str3 = '22222f22o22o22l2222';
str4 = '$$all$$for$$';
str5 = 'othmmmmmers.'

(1) 'all' in str1 is not capitalized, please modify it by subscript index;

(2) 'himself' in str2 is inverted, please modify it by string extraction;

(3) str3 contains the word 'fool', please extract this word;

(4) The original position of space in str4 is replaced by '$$', please use the string replacement function to replace it with space;

(5) 'mmmmm 'in str5 is redundant, please delete it;

(6) Combine str1-str5 into 'all the wise for himself, a cool all for others.', Use two methods to compare the string you get with the standard string standard to verify whether there is any error.


☆ thinking questions 2-8: four variables are known as follows. Complete the task as required.

var_1 = [82,91,13,92,64,10,28,55,96,97];
var_2 = {'str1',41,[30 20 10],'str2',70,[10,20;30,40],'str3','str4',uint8(4)};
var_3 = {'a','b','c','d','e'};
var_4 = 'abc';

(1) Set these four variables to 1 ∗ 2 1*2 1 * 2 is stored in the form of structure array, and the structure name is' struct2 '_ 8 ', the first two variables are stored in the first element of the structure array, and the last two variables are stored in the second element;

(2) Var access_ The first five elements in 1, the returned type is cell array; Access var_ The element'd 'in 3 returns a character type; Access var_ For the first three elements in 3, the returned type is cell array type;

(3) (difficult) extract var_2 character array type data, and form them into a 1 ∗ 4 1*4 1 * 4 cell array.


Answers to some thinking questions


Thinking questions 2-7

clc,clear all,close all
standard = 'All the wise for himself, a fool all for others.';
str1 = 'all the wise ';
str2 = 'for flesmih, a ';
str3 = '22222f22o22o22l2222';
str4 = '$$all$$for$$';
str5 = 'othmmmmmers.';

%% modify
str1(1) = 'A'
str2(5:11) = str2(11:-1:5)
str3 = str3(6:3:15)
str4 = strrep(str4,'$$',' ')
str5(4:8) = []
std_str = [str1,str2,str3,str4,str5]

%% Verify whether there are errors
%(1)
result1 = strcmp(standard,std_str) % The result is logical 1,Correct
%(2)
result2 = sum(std_str ~= standard) % Each element of the character array is the same, and the result is 0



Thinking questions 2-8

clc,clear all,close all
% First question
struct2_8(1,1).var_1 = {82,91,13,92,64,10,28,55,96,97};
struct2_8(1,1).var_2 = {'str1',41,[30 20 10],'str2',70,[10,20;30,40],'str3','str4',uint8(4)};
struct2_8(1,2).var_3 = {'a','b','c','d','e'};
struct2_8(1,2).var_4 = 'abc';
Q1_result = struct2_8

% Second question
Q2_result1 = struct2_8(1,1).var_1(1:5)
Q2_result2 = struct2_8(1,2).var_3{4}
Q2_result3 = struct2_8(1,2).var_3{4}

% Third question
Q3_result = cell(1,4);
j = 1;
for i = 1:length(struct2_8(1,1).var_2)
    if ischar(struct2_8(1,1).var_2{1,i})
        Q3_result{1,j} = struct2_8(1,1).var_2{1,i};
        j = j+1;
    end
end
Q3_result



Written by: Deng Yunze, Lin Yao
Reviewed by: staff of HelloWorld programming Association of central China Normal University

  1. Liu Hao, Han Jing MATLAB R2018a completely self-taught all-in-one [M] Beijing: Electronic Industry Press two thousand and nineteen ↩︎

  2. MATLAB advanced data structure serial 4 containers Map[EB/OL]. doi: https://zhuanlan.zhihu.com/p/22247363 ↩︎

Topics: MATLAB linear algebra