Matlab (variable and text reading)

Table of contents

1. Variable (data) type conversion

 1.1 characters

 1.2 String

1.3 Logical operations and assignments

2.Struct structure array

2.1 Detailed introduction of functions:

2.1.1 cell2struct

 2.1.1.1 Vertical dimension conversion

 2.1.1.2 Horizontal dimension conversion

2.1.1.3 section for conversion

2.1.2 rmfield

2.1.3 fieldnames (view attribute values ​​in the structure)

3. Nested structure

4.Cell cell array

 4.1 Creating objects and accessing them

4.2 Cell cell array function

4.2.1 num2cell (convert to cell array of the same size)

4.2.2 matcell (converted to a cell array containing subarrays in cells)

5. Multidimensional array

 5.1 cat() function

5.2 reshape() function

6.File access

6.1 save()

6.2 load()

7.Excel file reading

7.1 xlsread()

 7.2 xlswrite()

7.3 Low-level file input/output


1. Variable (data) type conversion

Common type conversions
double() Convert to double
single() Convert to single precision
int8() Convert to 8-bit signed integer
int16() Convert to 16-bit signed integer
int32() Convert to 32-bit signed integer
int64() Convert to 64-bit signed integer
uint8() Convert to 8-bit unsigned integer
uint16() Convert to 16-bit unsigned integer
uint32() Convert to 32-bit unsigned integer
uint64() Convert to 64-bit unsigned integer

In Matlab we can convert types directly:

 1.1 characters

       In Matlab, characters are expressions enclosed by quotes (single quotes or double quotes). Characters can include letters, numbers, symbols, and spaces. They are used to represent text data. Each character corresponds to an ASSCII code value.

ASCII code details

 1.2 String

       In MATLAB, a string is a sequence of characters enclosed by quotes (single or double quotes). Strings can contain letters, numbers, symbols, and spaces and are used to represent textual data.

 We talked about how to merge matrices before. Today we try to splice strings:

  • Use square brackets to concatenate

Horizontal splicing :

>> s1='Lingda'

s1 =

    'Lingda'

>> s2='lisi'

s2 =

    'lisi'
 
>> s3=[s1,s2]

s3 =

    'Lingdalisi'

 Vertical splicing :

       Obviously this method is wrong, because the lengths of the two strings are inconsistent, so the dimensions are inconsistent. This splicing method can only be spliced ​​if strings of the same length are consistent.

>> s3=[s1;s1]

s3 =

  2×6 char 数组

    'Lingda'
    'Lingda'
  • splicing using functions

Vertical splicing :

>> s3=vertcat(s1,s1)

s3 =

  2×6 char 数组

    'Lingda'
    'Lingda'

Horizontal splicing :

>> s3=horzcat(s1,s1)

s3 =

    'LingdaLingda'

>> s3=horzcat(s1,s2)

s3 =

    'Lingdalisi'

1.3 Logical operations and assignments

Each position in the array represents a corresponding index, and strings are no exception. A single character also corresponds to an index.

>> str='aadfgtaad'

str =

    'aadfgtaad'

>> str(3)

ans =

    'd'

The index position in Matlab starts from 1, so the position with index 3 is 'd'

Suppose we want to find the index where the character 'a' is? How to find it?

>> 'a'==str

ans =

  1×9 logical 数组

   1   1   0   0   0   0   1   1   0

>> str=='a'

ans =

  1×9 logical 数组

   1   1   0   0   0   0   1   1   0

In this search method, if there is a match, the index position will be 1, if not, it will be 0

If we need to compare two strings, we need to use the strcmp () function

>>  help strcmp
strcmp - 比较字符串

    此 MATLAB 函数 比较 s1 和 s2,如果二者相同,则返回 1 (true),否则返回 0
    (false)。如果文本的大小和内容相同,则它们将视为相等。返回结果 tf 的数据类型为 logical。

    tf = strcmp(s1,s2)
>> s1='happy'

s1 =

    'happy'

>> s2='happy'

s2 =

    'happy'

>> strcmp(s1,s2)

ans =

  logical

   1

How to reverse a string :

%方法一:
>> s1='I like beautiful gril'

s1 =

    'I like beautiful gril'

>> s2=s1(size(s1,2):-1:1)

s2 =

    'lirg lufituaeb ekil I'
%方法二:
>> s2=s1(length(s1):-1:1)

s2 =

    'lirg lufituaeb ekil I'

%方法三:

>> help reverse
reverse - 反转字符串中的字符顺序

    此 MATLAB 函数 反转 str 中字符的顺序。

    newStr = reverse(str)
>> reverse(s1)

ans =

    'lirg lufituaeb ekil I'
%方法四:
>> help flip
flip - 翻转元素顺序

    此 MATLAB 函数 返回的数组 B 具有与 A 相同的大小,但元素顺序已反转。B 中重新排序的维度取决于 A 的形状:

    B = flip(A)
    B = flip(A,dim)
>> flip(s2)

ans =

    'I like beautiful gril'

2. Struct structure array

       In MATLAB, a structure is a data type used to store and organize data . A structure consists of multiple fields, each of which can store different types of data.

Here are some basic operations on structures:

  • Create the structure:
s.field1 = value1;
s.field2 = value2;
  • Access structure fields:
value = s.field;
  • Update the value of a structure field:
s.field = new_value;
  • Delete structure fields:
s = rmfield(s, 'field');
  • Check whether the structure contains a field:
isfield(s, 'field');
  • Get the field names of the structure:
field_names = fieldnames(s);
  • Create an array of structures:
s(1).field = value1;
s(2).field = value2;
  • Access elements of a structure array:
value = s(index).field;

       Students who are familiar with Java can easily think of structures and classes in Java together. Both can store different data, objects and attributes.

Let's create a struct manually next:

>> student.name='Linda';
>> student.id=16;
>> student.number=2009014034;
>> student.grades=[80 70 60;50 90 70]

student = 

  包含以下字段的 struct:

      name: 'Linda'
        id: 16
    number: 2.0090e+09
    grades: [2×3 double]

We can get the specific value in the structure through .

>> student.grades

ans =

    80    70    60
    50    90    70
>> student.name

ans =

    'Linda'

       So is only one data allowed in the structure? NONONO, of course not, we just need to distinguish it from the first type of data.

>> student(2).name='Lisi';%用(number)进行区分
student(2).id=18;
student(2).number=2009014036;
>> student(2).grades=[90 50 60;40 80 60]

student = 

  包含以下字段的 1×2 struct 数组:

    name
    id
    number
    grades
>> student(2)

ans = 

  包含以下字段的 struct:

      name: 'Lisi'
        id: 18
    number: 2.0090e+09
    grades: [2×3 double]

>> student(1)

ans = 

  包含以下字段的 struct:

      name: 'Linda'
        id: 16
    number: 2.0090e+09
    grades: [2×3 double]
Commonly used functions in structures
cell2struct Convert cell array to structure array
fieldnames Field name of a structure or public field of an object
getfield Structure array fields
isfield Determine if the input is a structure array field
isstruct Determine if input is an array of structures
orderfields Order fields of structure array
rmfield Remove fields from structure
setfield Assign values ​​to structure array fields
struct Create array of structures
struct2cell Convert structure to cell array
structfun Apply a function to each field of a scalar structure

2.1 Detailed introduction of functions :

2.1.1 cell2struct

structArray = cell2struct(cellArray, fields, dim)
%structArray = cell2struct(cellArray, fields, dim) 通过元胞数组 cellArray 中包含的信息创建一个结构体数组 structArray。

%fields 参数指定结构体数组的字段名称。此参数是一个字符数组、字符向量元胞数组或字符串数组。

%dim 参数向 MATLAB® 指示创建结构体数组时要使用的元胞数组的轴。使用数值 double 指定 dim。

Case:

 Create an initial cell array of employees :

>> devel = {
   
   {'Lee','Reed','Hill'}, {'Dean','Frye'}, ...
   {'Lane','Fox','King'}};
sales = {
   
   {'Howe','Burns'}, {'Kirby','Ford'}, {'Hall'}};
mgmt = {
   
   {'Price'}, {'Clark','Shea'}, {'Sims'}};
qual = {
   
   {'Bates','Gray'}, {'Nash'}, {'Kay','Chase'}};
docu = {
   
   {'Lloyd','Young'}, {'Ryan','Hart','Roy'}, {'Marsh'}};
>> employees = [devel; sales; mgmt; qual; docu]

employees =

  5×3 cell 数组

    {1×3 cell}    {1×2 cell}    {1×3 cell}
    {1×2 cell}    {1×2 cell}    {1×1 cell}
    {1×1 cell}    {1×2 cell}    {1×1 cell}
    {1×2 cell}    {1×1 cell}    {1×2 cell}
    {1×2 cell}    {1×3 cell}    {1×1 cell}

 2.1.1.1 Vertical dimension conversion

 Convert a cell array to a structure along dimension 1 (the vertical dimension ):

 We need to customize the header for each row in the vertical dimension:

>> rowTitles={'development', 'sales', 'management','quality', 'documentation'}

rowTitles =

  1×5 cell 数组

    {'development'}    {'sales'}    {'management'}    {'quality'}    {'documentation'}

Convert the cell array to the structure array dept related to this dimension:

>> depts = cell2struct(employees, rowTitles, 1)

depts = 

  包含以下字段的 3×1 struct 数组:

    development
    sales
    management
    quality
    documentation

Find a specific numerical value:

>> depts(2:3).development%先确定行再确定哪个属性

ans =

  1×2 cell 数组

    {'Dean'}    {'Frye'}


ans =

  1×3 cell 数组

    {'Lane'}    {'Fox'}    {'King'}

 2.1.1.2 Horizontal dimension conversion

Convert the cell array to a structure along dimension 2 (the horizontal dimension ):

  We need to customize the header for each row in the horizontal dimension:

>> colHeadings = {'fiveYears' 'tenYears' 'fifteenYears'}

colHeadings =

  1×3 cell 数组

    {'fiveYears'}    {'tenYears'}    {'fifteenYears'}

Convert the cell array to the structure array dept related to this dimension:

>> years = cell2struct(employees, colHeadings, 2)

years = 

  包含以下字段的 5×1 struct 数组:

    fiveYears
    tenYears
    fifteenYears

When using a column structure, the number of employees in the sales and documentation departments who have been with the company for at least 5 years will be displayed.

 [~, sales_5years, ~, ~, docu_5years] = years.fiveYears

sales_5years =

  1×2 cell 数组

    {'Howe'}    {'Burns'}


docu_5years =

  1×2 cell 数组

    {'Lloyd'}    {'Young'}

When searching above, use placeholders for unnecessary columns, otherwise an error will occur:

 [ sales_5years, docu_5years] = years.fiveYears

sales_5years =

  1×3 cell 数组

    {'Lee'}    {'Reed'}    {'Hill'}


docu_5years =

  1×2 cell 数组

    {'Howe'}    {'Burns'}

2.1.1.3 section for conversion

What do we do if we only want to convert the first and last rows of a cell array?

>> rowTitlesOnly={'develop','document'}

rowTitlesOnly =

  1×2 cell 数组

    {'develop'}    {'document'}

>> depts=cell2struct(employees([1,5],:),rowTitlesOnly,1)

depts = 

  包含以下字段的 3×1 struct 数组:

    develop
    document

 If we want to know who is in the structure, we only need to solve it like this:

>> for k=1:3
   depts(k,:)
end

ans = 

  包含以下字段的 struct:

     develop: {'Lee'  'Reed'  'Hill'}
    document: {'Lloyd'  'Young'}


ans = 

  包含以下字段的 struct:

     develop: {'Dean'  'Frye'}
    document: {'Ryan'  'Hart'  'Roy'}


ans = 

  包含以下字段的 struct:

     develop: {'Lane'  'Fox'  'King'}
    document: {'Marsh'}

2.1.2 rmfield

Delete some fields in the structure

>> depts

depts = 

  包含以下字段的 3×1 struct 数组:

    develop
    document
>> rmfield(depts,'develop')

ans = 

  包含以下字段的 3×1 struct 数组:
    document

2.1.3 fieldnames (view attribute values ​​in the structure)

>> fieldnames(depts)

ans =

  2×1 cell 数组

    {'develop' }
    {'document'}

3. Nested structure

        Nested structure in Matlab refers to nesting one structure within another structure. In this way, more complex data structures can be created to better organize and manage the data. Nested structures can access the fields of the inner structure by using the dot operator.

>> A = struct('data', [3 4 7; 8 0 1], 'nest', ...
struct('testnum', 'Test 1', ...
'xdata', [4 2 8],'ydata', [7 1 6]));
A(2).data = [9 3 2; 7 6 5];
A(2).nest.testnum = 'Test 2';
A(2).nest.xdata = [3 4 2];
A(2).nest.ydata = [5 0 9];
A.nest

ans = 

  包含以下字段的 struct:

    testnum: 'Test 1'
      xdata: [4 2 8]
      ydata: [7 1 6]


ans = 

  包含以下字段的 struct:

    testnum: 'Test 2'
      xdata: [3 4 2]
      ydata: [5 0 9]
>> A(1).data

ans =

     3     4     7
     8     0     1

>> A(2).data

ans =

     9     3     2
     7     6     5

>> A(1).nest.testnum%结构体中的结构体

ans =

    'Test 1'

4.Cell cell array

  1. Another way to store heterogeneous data
  2. Similar to a matrix, but each entry contains different types of data
  3. A set of cells can be referenced by enclosing the index in parentheses (), allowing curly braces {} to index to access the contents of the cell

 4.1 Creating objects and accessing them

Method one :

>> A(1,1)={[1 4 3; 0 5 8; 7 2 9]};
A(1,2)={'Anne Smith'};
A(2,1)={3+7i};
A(2,2)={-pi:pi:pi};
A

A =

  2×2 cell 数组

    {3×3 double        }    {'Anne Smith'}
    {[3.0000 + 7.0000i]}    {1×3 double  }

Method two :

>> A{1,1}=[1 4 3; 0 5 8; 7 2 9];
A{1,2}='Anne Smith';
A{2,1}=3+7i;
A{2,2}=-pi:pi:pi;
A

A =

  2×2 cell 数组

    {3×3 double        }    {'Anne Smith'}
    {[3.0000 + 7.0000i]}    {1×3 double  }

Why can Cell array accurately find the corresponding value?

  • Each entry in the cell array holds a pointer to the data structure
  • Different cells of the same cell array can point to different types of data structures

>> C=A(1,1)

C =

  1×1 cell 数组

    {3×3 double}

>> C=A{1,1}%{}显示具体的元素

C =

     1     4     3
     0     5     8
     7     2     9

4.2 Cell cell array function

Cell cell array function
cell Create cell array
cell2mat Convert a cell array to an ordinary array of underlying data types
cell2struct Convert cell array to structure array
celldisp Display the contents of a cell array
cellfun Apply a function to each cell in a cell array
cell plot Graphically display the structure of a cell array
cellstr Convert to cell array of character vectors
iscell Determine if input is a cell array
mat2cell Convert an array to a cell array containing subarrays within cells
num2cell Convert an array to a cell array of the same size
struct2cell Convert structure to cell array

4.2.1 num2cell (convert to cell array of the same size)

%C = num2cell(A) 通过将 A 的每个元素放置于 C 的一个单独元胞中,来将数组 A 转换为元胞数组 C。num2cell 函数转换具有任意数据类型(甚至是非数值类型)的数组。
C = num2cell(A)
%C = num2cell(A,dim) 将 A 的内容划分成 C 中单独的元胞,其中 dim 指定每个元胞包含 A 的哪个维度。
C = num2cell(A,dim)

 Case implementation :

%数字元胞数组
>> a=magic(3)

a =

     8     1     6
     3     5     7
     4     9     2

>> C=num2cell(a)

C =

  3×3 cell 数组

    {[8]}    {[1]}    {[6]}
    {[3]}    {[5]}    {[7]}
    {[4]}    {[9]}    {[2]}
%字符串元胞数组
>> a = ['four';'five';'nine']

a =

  3×4 char 数组

    'four'
    'five'
    'nine'

>> c = num2cell(a)

c =

  3×4 cell 数组

    {'f'}    {'o'}    {'u'}    {'r'}
    {'f'}    {'i'}    {'v'}    {'e'}
    {'n'}    {'i'}    {'n'}    {'e'}

4.2.2 matcell (converted to a cell array containing subarrays in cells)

%C = mat2cell(A,dim1Dist,...,dimNDist) 将数组 A 划分为更小的数组,并在元胞数组 C 中返回它们。向量 dim1Dist,...dimNDist 指定如何划分 A 的行、列和(如果适用)更高维度。C 中较小的数组可以具有不同大小。A 可以包含任何数据类型。
C = mat2cell(A,dim1Dist,...,dimNDist)
%C = mat2cell(A,rowDist) 将数组 A 划分为一个 n×1 元胞数组 C,其中 n 等于 rowDist 中元素的数量。
C = mat2cell(A,rowDist)

For example: If A is a 60*50 array, you can specify this parameter as [10 20 30], [25 25] to divide A, as shown above:

>> A=rand(60,50);
>> C=mat2cell(A,[10 20 30],[25 25])

C =

  3×2 cell 数组

    {10×25 double}    {10×25 double}
    {20×25 double}    {20×25 double}
    {30×25 double}    {30×25 double}

        For  A the th  K dimension, when specifying the elements of the corresponding vector  dimKDist , it must be  sum(dimKDist) equal to  K the size of the th dimension . If  the size of A the th  K dimension is zero, the corresponding vector should  dimKDist be specified as an empty array  [], as shown in the code.

>> A = rand(3,0,4);
C = mat2cell(A,[1 2],[],[2 1 1])

C =

  空的 2×0×3 cell 数组

5. Multidimensional array

 5.1 cat() function

>> A=[1 2;3 4]; B=[5 6;7 8];
>> C=cat(1,A,B)

C =

     1     2
     3     4
     5     6
     7     8

>> C=cat(2,A,B)

C =

     1     2     5     6
     3     4     7     8

>> C=cat(3,A,B)

C(:,:,1) =

     1     2
     3     4


C(:,:,2) =

     5     6
     7     8

5.2 reshape() function

%B = reshape(A,sz) 使用大小向量 sz 重构 A 以定义 size(B)。例如,reshape(A,[2,3]) 将 A 重构为一个 2×3 矩阵。sz 必须至少包含 2 个元素,prod(sz) 必须与 numel(A) 相同。
B = reshape(A,sz)
%B = reshape(A,sz1,...,szN) 将 A 重构为一个 sz1×...×szN 数组,其中 sz1,...,szN 指示每个维度的大小。可以指定 [] 的单个维度大小,以便自动计算维度大小,以使 B 中的元素数与 A 中的元素数相匹配。例如,如果 A 是一个 10×10 矩阵,则 reshape(A,2,2,[]) 将 A 的 100 个元素重构为一个 2×2×25 数组
B = reshape(A,sz1,...,szN)

>> A=[1 2 3 4 5 6 7 8 9]

A =

     1     2     3     4     5     6     7     8     9

>> B=reshape(A,[3,3])%重新分配成3*3的数组

B =

     1     4     7
     2     5     8
     3     6     9
>> A=magic(4)

A =

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

>> B=reshape(A,[],2)%可以指定 [] 的单个维度大小,以便自动计算维度大小,以使 B 中的元素数与 A 中的元素数相匹配

B =

    16     3
     5    10
     9     6
     4    15
     2    13
    11     8
     7    12
    14     1
Functions to check variables and variable status
syntax Determine if the input is an array of integers
islogical Determine whether the input is a logical array
isan Detect non-numeric elements (NaN)
isnumeric Determine if input is a numeric array
they receive Detect prime elements of an array
Israel Determine if all array elements are real numbers
iscell Determine if input is a cell array
ischar Determine if input is a character array
isempty Determine if input is an empty array
isequal Determine whether arrays are numerically equal
isfloat Determine if the input is a floating point array
isglobal Determine if input is a global variable
handle Detects a valid graphics object handle
for you Detect infinite elements of an array

6.File access

Matlab is equivalent to an intermediate processing factory (calculation). We need to save its calculation results in our files.

6.1 save()

  • Without -ascii

 

 When opened, it is garbled (compressed). This mode of storage is inconvenient for us to view manually.

  • add-ascii

 This method of storage is easier for us to identify

6.2 load()

       When reading a file, if you use save -ascii to store it, you also need to load -ascii when downloading.

7.Excel file reading

7.1 xlsread()

Note: All read Excel tables should be in the same folder as the running file. When reading, only the numeric part can be read by default, and the reading of the string part is automatically omitted.

 

 7.2 xlswrite()

We need to calculate the average and write it in the spreadsheet

>> help mean
mean - 数组的均值

    此 MATLAB 函数 返回 A 沿大小不等于 1 的第一个数组维度的元素的均值。

    M = mean(A)
    M = mean(A,'all')
    M = mean(A,dim)
    M = mean(A,vecdim)
    M = mean(___,outtype)
    M = mean(___,nanflag)
>> M=mean(Score')'%mean是以列为单位进行计算,我们首先对元素数组取转置,然后再进行计算

M =

    86
    98
    85
xlswrite('Score.xlsx',M,1,'E2:E4')

 

  xlswrite('Score.xlsx',{'平均值'},1,'E1')%写列题目

 So how should we get the text in the Excel table?

>> [Score Header]=xlsread('Score.xlsx')

Score =

    95    83    80    86
   100    98    96    98
    80    94    81    85


Header =

  4×5 cell 数组

    {0×0 char}    {'语文'  }    {'数学'  }    {'英语'  }    {'平均值' }
    {'小飞'  }    {0×0 char}    {0×0 char}    {0×0 char}    {0×0 char}
    {'小刘'  }    {0×0 char}    {0×0 char}    {0×0 char}    {0×0 char}
    {'小鹏'  }    {0×0 char}    {0×0 char}    {0×0 char}    {0×0 char}

7.3 Low-level file input/output

  • Read and write files at the byte or character level
  • The file ID is fid
  • The position in the file is specified by a movable pointer

Low-level file I/O functions
function describe
fopen Open a file, or get information about open files
fclose Close one or all open files
fscanf Read data from text file
fprintf Write data to text file
feof End of test file

Open and close files:

fid=fopen('[filename]','[permission]');%打开文件
permission: 'r' 'r+' 'w' 'w+' 'a' 'a+'
'r':只读,默认
'w':只写,覆盖原内容
'a':附加数据到文件尾部
'r+':读与写
'w+':读与写,写时覆盖原内容
'a+':读与写,写时,附加到文件尾部
status=fclose(fid);%关闭文件

Case:

Write cosine values ​​to a file:

>> x=0:pi/10:pi;
y=cos(x);
fid=fopen('cos.txt','w');
for i=1:11
      fprintf(fid,'%5.3f %8.4f\n',x(i),y(i));
end
>> fclose(fid);
>> type cos.txt

 IO read and write operations:

 Read file:

>> fid = fopen('Date.txt','r'); i = 1;
while ~feof(fid)
name(i,:) = fscanf(fid,'%5c',1);
year(i)= fscanf(fid,'%d',1);
no1(i) = fscanf(fid,'%d',1);
no2(i) = fscanf(fid,'%d',1);
no3(i) = fscanf(fid,'%g',1);
no4(i) = fscanf(fid,'%g\n');
i=i+1;
end
fclose(fid);

Guess you like

Origin blog.csdn.net/dfdbb6b/article/details/132553963