MATLAB 变量数据类型与文件读写

本文详细介绍了MATLAB中的数据类型,包括默认的double、int8、uint8,以及变量类型转换、字符(char)、ASCII TABLE、字符串、逻辑运算、结构体、单元阵列、多维数组、文件处理等。特别讨论了结构体的使用,如添加信息、字段操作以及嵌套结构,并提供了单元数组访问和低级文件输入/输出的示例。此外,还涵盖了Excel文件的读写操作,如xlsread和xlswrite函数的运用。
摘要由CSDN通过智能技术生成


前言

b站课程《MATLAB教程_台大郭彦甫(14课)》学习记录


第一部分

一、MATLAB Data (Variables) Types

在这里插入图片描述
default(默认的)为double

int8 8-bit

uint8 unsigned

二、Variable (Data) Type Conversion 变量(数据)类型转换

在这里插入图片描述

>> A = 20
A =
    20
>> B = int8(20)
B =
  int8
   20
>> B = int8(A)
B =
  int8
   20

三、Character (char)

A character is represented in ASCII using a numeric code between 0 to 255
字符在ASCII中使用0到255之间的数字代码表示
Create a character or a string by putting them into a pair of apostrophe:
创建一个字符或字符串,将它们放入一对单引号:

>> s1 = 'h'
whos
uint16(s1)
s2 = 'H'
whos
uint16(s2)
s1 =
    'h'
  Name      Size            Bytes  Class     Attributes
  A         1x1                 8  double              
  B         1x1                 1  int8                
  ans       1x1                 2  uint16              
  s1        1x1                 2  char                
ans =
  uint16
   104
s2 =
    'H'
  Name      Size            Bytes  Class     Attributes
  A         1x1                 8  double              
  B         1x1                 1  int8                
  ans       1x1                 2  uint16              
  s1        1x1                 2  char                
  s2        1x1                 2  char                
ans =
  uint16
   72

四、ASCII TABLE

在这里插入图片描述

五、String 字符串

An array collects characters:
数组用于收集字符:

s1 = 'Example';
s2 = 'String';

String concatenation:
字符串连接

s3 = [s1 s2];
s4 = [s1; s2];
>> s1 = 'Example';
>> s2 = 'String';
>> s3 = [s1 s2];
>> s3
s3 =
    'ExampleString'

>> s4 = [s1;s2];
要串联的数组的维度不一致。

>> s4 = [s1;s1];
>> s4
s4 =
  2×7 char 数组
    'Example'
    'Example'

六、Logical Operations and Assignments 逻辑运算及分配

Many numerical and logical operators can be applied to strings
许多数值和逻辑运算符可应用于字符串

>> str = 'aardvark';
>> str(3)
ans =
    'r'
>> 'a' == str
ans =
  1×8 logical 数组
   1   1   0   0   0   1   0   0

进行逻辑运算,相同为True1,不同为False0
Try this:

>> str(str == 'a') = 'Z'
str =
    'ZZrdvZrk'

将str中为’a’的字符更换成’Z’
What if we want to compare the entire string with another?
可以用循环语句,for

Exercise

Write a script that inverts any given string
在这里插入图片描述
方法一:

s1 = 'I like the letter E';
s2 = blanks(size(s1,2));  (生成一个空白的数组)
%size(char),char是字符向量,返回行向量【1 N】
%strlength(s1)在R2016b以上版本中才可用
s2 = s1(size(s1,2):-1:1);
disp(s2)

方法二:

s1 = 'I like the letter E';
s2 = blanks(size(s1,2));
for n = 1:1:size(s1,2)
    s2(n) = s1(size(s1,2)-n+1);
    n+1;
end
disp(s2)

最好不用zeros来生成s2,因为他会直接把数组都定义为double类型的
方法三:

s1 = 'I like the letter E';
s2 = char(zeros(1,size(s1,2)));  将zeros由double型变成char型,就可以存放字符了
for n = 1:1:size(s1,2)
    s2(n) = s1(size(s1,2)-n+1);
    n+1;
end
disp(s2)

七、Structure 结构体

A method of storing heterogeneous data
一种存储异构数据的方法
Structures contain arrays called fields
结构包含称为字段的数组
Student assignment grades:
在这里插入图片描述
Adding Information to A Structure

>> student.name = 'John Doe';
student.id = 'jdo2@sfu.ca';
student.number = 301073268;
student.grade = [100, 75, 73; ...
    95, 91, 85.5; ...
    100, 98, 72];
student
student = 
  包含以下字段的 struct:
      name: 'John Doe'
        id: 'jdo2@sfu.ca'
    number: 301073268
     grade: [3×3 double]
>> student.name = 'John Doe';
student.id = 'jdo2@sfu.ca';
student.number = 301073268;
student.grade = [100, 75, 73; ...
    95, 91, 85.5; ...
    100, 98, 72];
student(2).name = 'Ann Lane'; 
student(2).id = 'aln4@sfu.ca';
student(2).number = 301078853;
student(2).grade = [95 100 90; 95 82 97; 100 85 100];
>> student
student = 
  包含以下字段的 1×2 struct 数组:
    name
    id
    number
    grade

Retrieve the 3rd grade for Ann Lane

在这里插入图片描述

>> student(2).grade(1,3)
ans =
    90
Structure Functions

八、Structure Functions 结构体函数

cell2struct : Convert cell array to structure array
fieldnames : Field names of structure, or public fields of object
getfield : Field of structure array
isfield : Determine whether input is structure array field
isstruct : Determine whether input is structure array
orderfields : Order fields of structure array
rmfield : Remove fields from structure
setfield : Assign values to structure array field
struct : Create structure array
struct2cell : Convert structure to cell array
structfun : Apply function to each field of scalar structure
cell2struct : 将单元数组转换为结构数组
fieldnames : 结构或对象的公共字段的字段名
getfield : 结构数组的字段
isfield : 判断input是否为结构数组字段
isstruct : 判断输入是否为结构数组
orderfields : 结构数组的顺序字段
rmfield : 从结构中删除字段
setfield : 为结构数组字段赋值
struct : 创建结构数组
struct2cell : 将结构转换为单元格数组
structfun : 对标量结构的每个字段应用函数

>> fieldnames(student)
rmfield(student,'id')
ans =
  4×1 cell 数组

    {'name'  }
    {'id'    }
    {'number'}
    {'grade' }
ans = 
  包含以下字段的 1×2 struct 数组:
    name
    number
    grade

九、Nesting Structures 嵌套结构

在这里插入图片描述
在一个Structure 里面有另一个Structure

>> 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]

十、Cell Array 单元阵列

Another method of storing heterogeneous data
另一种存储异构数据的方法
Similar to matrix but each entry contains different type of data
类似于矩阵,但每个条目包含不同类型的数据
Declared using { }
使用{}声明
在这里插入图片描述

>> 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]}    {[-3.1416 0 3.1416]}
>> clear A
>> 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]}    {[-3.1416 0 3.1416]}

十一、How Does MATLAB Do It?

Each entry in a cell array holds a pointer to a data structure
单元格数组中的每一项都包含一个指向数据结构的指针
Different cells of the same cell array can point to different types of data structures
同一单元数组的不同单元可以指向不同类型的数据结构
在这里插入图片描述

Exercise

Create a cell array B that has the following structure
在这里插入图片描述

>> B{1,1} = 'This is the first cell';
B{1,2} = [5+j*6 4+j*5];
B{2,1} = [1 2 3; 4 5 6; 7 8 9];
B{2,2} = {'Tim', 'Chris'};
B
B =
  2×2 cell 数组
    {'This is the first cell'}    {[5.0000 + 6.0000i 4.0000 + 5.0000i]}
    {3×3 double              }    {1×2 cell                           }

十二、Accessing Cell Array 访问单元阵列

Curly braces, { }, are used to access the “content” of cell arrays
花括号{}用于访问单元格数组的“内容”
• What are the differences between C and D?

C = A(1,1)
D = A{1,1}
>> C = A(1,1);
>> D = A{1,1};
>> C
C =
  1×1 cell 数组
    {3×3 double}
>> D
D =
     1     4     3
     0     5     8
     7     2     9

• How do I get this number?
在这里插入图片描述

>> A{1,1}(1,1)
ans =
     1

十三、Cell Array Functions 单元阵列函数

cell : Create cell array
cell2mat : Convert cell array to numeric array
cell2struct : Convert cell array to structure array
celldisp : Cell array contents
cellfun : Apply function to each cell in cell array
cellplot : Graphically display structure of cell array
cellstr : Create cell array of strings from character array
iscell : Determine whether input is cell array
mat2cell : Convert array to cell array with different sized cells
num2cell : Convert array to cell array with consistently sized cells
struct2cell : Convert structure to cell array
cell : 创建单元格数组
cell2mat : 将单元数组转换为数值数组
cell2struct : 将单元数组转换为结构数组
celldisp : 单元格数组内容
cellfun : 将函数应用到数组中的每个cell
cellplot : 细胞图图形显示细胞阵列的结构
cellstr : 从字符数组中创建字符串的单元格数组
iscell : 判断输入是否为cell array
mat2cell : 将数组转换为不同大小的单元格数组
num2cell : 将数组转换为单元格大小一致的单元格数组
struct2cell : 将结构转换为单元格数组

十四、num2cell() and mat2cell()

Transform a matrix into a cell variable

>> a = magic(3)
b = num2cell(a)
c = mat2cell(a, [1 1 1], 3)     
第二个为row,第三个为column;说明行分成三份,列不分开
a =
     8     1     6
     3     5     7
     4     9     2
b =
  3×3 cell 数组
    {[8]}    {[1]}    {[6]}
    {[3]}    {[5]}    {[7]}
    {[4]}    {[9]}    {[2]}
c =
  3×1 cell 数组
    {[8 1 6]}
    {[3 5 7]}
    {[4 9 2]}

在这里插入图片描述

十五、Multidimensional Array 多维数组

在这里插入图片描述

>> A{1,1,1} = [1 2;4 5]; 
A{1,2,1} = 'Name'; 
A{2,1,1} = 2-4i; 
A{2,1,1} = 7; 
A{1,1,2} = 'Name2'; 
A{1,2,2} = 3; 
A{2,1,2} = 0:1:3; 
A{2,2,2} = [4 5]';
A
  2×2×2 cell 数组
A(:,:,1) = 
    {2×2 double}    {'Name'    }
    {[       7]}    {0×0 double}
A(:,:,2) = 
    {'Name2'  }    {[       3]}
    {[0 1 2 3]}    {2×1 double}

十六、cat()

Array concatenation 数组连接

在这里插入图片描述

十七、Multidimensional Array concatenation 多维数组连接

在这里插入图片描述

十八、reshape()

Returns a new array with assigned rows and columns
返回具有指定行和列的新数组

>> A = {'James Bond', [1 2;3 4;5 6]; pi, magic(5)}
C = reshape(A,1,4)
A =
  2×2 cell 数组
    {'James Bond'}    {3×2 double}
    {[    3.1416]}    {5×5 double}
C =
  1×4 cell 数组
    {'James Bond'}    {[3.1416]}    {3×2 double}    {5×5 double}

Create a matrix B from the matrix A below using reshape:
在这里插入图片描述

>> A = [1:3;4:6];
B = reshape(A,3,2)
B =
     1     5
     4     3
     2     6

十九、Checking Variable And Variable Status 检查变量和变量状态

isinteger : Determine if input is integer array
islogical : Determine if input is logical array
isnan : Detect an element that isnot a number (NaN)
isnumeric : Determine if input is numeric array
isprime : Detect prime elements of array
isreal : Determine if all array elements are real numbers
iscell : Determine if input is cell array
ischar : Determine if input is character array
isempty : Determine if input is empty array
isequal : Determine if arrays are numerically equal
isfloat : Determine if input is floating-point array
isglobal : Determine if input is global variable
ishandle : Detect valid graphics object handles
isinf : Detect infinite elements of array
isinteger : 判断input是否为整数数组
islogical : 判断输入是否为逻辑阵列
isnan : 检测非数字元素(NaN)
isnumeric : 判断input是否为数值数组
isprime : 检测数组的素数元素
isreal : 判断是否所有数组元素都是实数
iscell : 判断input是否为cell array
ischar : 判断input是否为字符数组
isempty : 判断input是否为空数组
isequal : 判断数组在数值上是否相等
isfloat : 判断input是否为浮点数组
isglobal : 判断input是否为全局变量
ishandle : 检测有效的图形对象句柄
isinf : 检测数组的无限元素

第二部分

一、File Access 文件处理

在这里插入图片描述

二、save() and load()

在这里插入图片描述
其中两种方法的区别:
第一种,保存信息更全面,变量名在读取时会出现,但是不能在记事本中看到
第二种,保存信息没那么全面,变量名在读取时不会出现,但能在记事本中看到
保存指定变量到当前工作目录
1 若有一个变量aaa,想保存起来(mat文件,名字为a,即a.mat)方便下次调用。可用命令:
save a.mat A
在这里插入图片描述
2 保存当前所有变量到当前工作目录
在这里插入图片描述
3 保存指定变量到指定文件夹
save(‘C:\MATLAB\hello1.mat’,‘aaa’)
在这里插入图片描述

三、Excel File Reading: xlsread()

>> Score = xlsread('04Score.xlsx')
Score =
    94    83    89
    76    88    82
    68    72    75
>> Score = xlsread('04Score.xlsx','B2:D4')
Score =
    94    83    89
    76    88    82
    68    72    75

都只读取数字部分

四、Excel File Writing: xlswrite()

Calculate the means and write into Excel spreadsheet
计算平均值并写入Excel电子表格
在这里插入图片描述

filename  variable/name  sheet location
M = mean(Score')';
xlswrite('04Score.xlsx', M, 1, 'E2:E4');
xlswrite('04Score.xlsx', {'Mean'}, 1, 'E1');

Calculate the standard deviations and write them into column F
计算标准差,把它们写进F列

M = std(Score')';
xlswrite('04Score.xlsx', M, 1, 'F2:F4');
xlswrite('04Score.xlsx', {'standard deviations'}, 1, 'F1');

五、Getting Text in Excel Spreadsheet 获取文本在Excel电子表格

Getting both the text and numbers

>> [Score Header] = xlsread('04Score.xlsx')
Score =
  列 1 至 4
   94.0000   83.0000   89.0000   88.6667
   76.0000   88.0000   82.0000   82.0000
   68.0000   72.0000   75.0000   71.6667
  列 5
    5.5076
    6.0000
    3.5119
Header =
  4×6 cell 数组
  列 1 至 2
    {0×0 char}    {'Test1' }
    {'John'  }    {0×0 char}
    {'Selina'}    {0×0 char}
    {'Peter' }    {0×0 char}
  列 3 至 4
    {'Test2' }    {'Test3' }
    {0×0 char}    {0×0 char}
    {0×0 char}    {0×0 char}
    {0×0 char}    {0×0 char}
  列 5 至 6
    {'Mean'  }    {'standard deviat…'}
    {0×0 char}    {0×0 char           }
    {0×0 char}    {0×0 char           }
    {0×0 char}    {0×0 char           }
>> [Score Header] = xlsread('04Score.xlsx')
Score =
   94.0000   83.0000   89.0000   88.6667    5.5076
   76.0000   88.0000   82.0000   82.0000    6.0000
   68.0000   72.0000   75.0000   71.6667    3.5119
Header =
  4×6 cell 数组
  列 1 至 5
    {0×0 char}    {'Test1' }    {'Test2' }    {'Test3' }    {'Mean'  }
    {'John'  }    {0×0 char}    {0×0 char}    {0×0 char}    {0×0 char}
    {'Selina'}    {0×0 char}    {0×0 char}    {0×0 char}    {0×0 char}
    {'Peter' }    {0×0 char}    {0×0 char}    {0×0 char}    {0×0 char}
  列 6
    {'standard deviat…'}
    {0×0 char           }
    {0×0 char           }
    {0×0 char           }

How do we write both the text and number into an Excel file?

a=Header;
b=num2cell(Score);
xlswrite('a.xlsx',a,1,'A1:F4');
xlswrite('a.xlsx',b,1,'B2:F4');

六、Low-level File Input/Output 低级文件输入/输出

Read and write file at the byte or character level
低级字节级或字符级的读写文件
A file has an ID fid
一个文件有一个ID fid
Location in the file is specified by a pointer that can be moved around
在这里插入图片描述

七、Low-level File I/O Functions 低级文件输入输出函数

在这里插入图片描述

八、Writing Sine Values into A File 将正弦值写入文件

>> x = 0:pi/10:pi; 
y = sin(x); 
fid = fopen('sinx.txt','w');
for i=1:11
    fprintf(fid,'%5.3f %8.4f\n', x(i), y(i));  【五位数值,三个小数点;八位数值,四个小数点】
end
fclose(fid); 
type sinx.txt
0.000   0.0000
0.314   0.3090
0.628   0.5878
0.942   0.8090
1.257   0.9511
1.571   1.0000
1.885   0.9511
2.199   0.8090
2.513   0.5878
2.827   0.3090
3.142   0.0000

在这里插入图片描述
在这里插入图片描述

九、Read and Write through Formatted I/O 通过格式化的I/O进行读写

在这里插入图片描述

十、Reading from Files

在这里插入图片描述

fid = fopen('04asciiData.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);

在这里插入图片描述


总结

继续加油吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值