三、变量与档案存取
-
变量
1.1 变量类型
类型 logical 逻辑类型 char 字符型 numeric int、uint、single、double… cell struct 结构体类型 1.2 强制类型转换
double()、single()、int8()…int64()、uint8()…uint64()
1.3 char类型——ASCII码保存
>> s1='Example'; s2='String'; >> s3=[s1 s2] s3 = 'ExampleString' >> s4=[s1;s2] #s1,s2长度不同,即维度不同,无法vertcat 错误使用 vertcat 要串联的数组的维度不一致。 >> s5=[s1;s1] s5 = 2×7 char 数组 'Example' 'Example'
char可进行逻辑运算
>> str='a'; >> str(str=='a')='z' #此时括号内逻辑值为1 str = 'z'
1.4 structure类型——结构体
>> student.name='John'; #matlab中结构体的创建,不用定义结构 student.id='123'; student.grade=[90,100,75;... 95,71,90;... 100,98,72]; >> student #结构体查询 student = 包含以下字段的 struct: name: 'John' id: '123' grade: [3×3 double] >> student.grade #调用结构体中的某元素 ans = 90 100 75 95 71 90 100 98 72 >> student(2).name='Lane'; #通过小括号创建一个同为student类型的2号 student(2).id='321'; student(2).grade=[95 100 90;95 82 97;100 85 100]; >> student #调用student显示1x2,有两个对象 student = 包含以下字段的 1×2 struct 数组: name id grade
1.5 常用结构体函数
Name Function Name Function cell2struct 元胞数组→结构体数组 rmfield(struct,x) 移除struct里的x元素 fieldnames(struct) 结构体元素 setfield getfield struct isfield struct2cell 结构体数组→元胞数组 isstruct structfun orderfields >> fieldnames(student) ans = 3×1 cell 数组 {'name' } {'id' } {'grade'} >> rmfield(student,'id') #删除元素 ans = 包含以下字段的 1×2 struct 数组: name grade
1.6 嵌套结构体——结构体内部的元素也可以是另一个结构体
>> A=struct('data',[3 4 7;8 0 1],'nest',... #结构体直接赋值:名字,数据 struct('testnum','Test 1',... #内部嵌套的结构体nest 'xdata',[4 2 8],'ydata',[7 1 6])); A(2).data=[9 3 2;7 6 5]; #定义结构体A的2号 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]
1.7 单元数组——使用 {} 大括号来声明
#单元数组中的数据可以是各种类型,每个单元格内的数据类型都是独立的
#方法一:{}放在后面 >> 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{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 } #读取单元数组内容 >> A(1,1) #小括号无法读取矩阵内部数据 ans = 1×1 cell 数组 {3×3 double} >> A{1,1} #利用大括号可以读取矩阵元素内容 ans = 1 4 3 0 5 8 7 2 9 >> A{1,1}(1,2) #将A{1,1}看成一个矩阵,则后面的小括号可读取矩阵内部某一个元素 ans = 4
1.8 常用单元数组函数
Name Function Name Function cell 创建cell cellstr Create cell array of strings from character array cell2mat cell array→numeric array iscell 判断是否为cell array cell2struct cell array→struct array mat2cell Convert array to cell array with different sized cells celldisp num2cell Convert array to cell array with consistently sized cells cellfun Apply function to each cell in cell array struct2cell Convert structure to cell array cellplot Graphically display structure of cell array #num2cell()和mat2cell()的使用 >> a=magic(3) #magic(n)-产生魔方矩阵,元素在1-n^2,它的每行、列以及对角线的数之和相等 a = 8 1 6 3 5 7 4 9 2 >> b=num2cell(a) b = 3×3 cell 数组 {[8]} {[1]} {[6]} {[3]} {[5]} {[7]} {[4]} {[9]} {[2]} >> c=mat2cell(a,[1 1 1],3) #(数组,行,列),行指定行如何分配,列指定列的分配方式 c = 3×1 cell 数组 {1×3 double} {1×3 double} {1×3 double}
1.9 多维度数组的处理
#cat(x,A,B)-concatenation,将A,B相接,x表示相接的方法:1=行(竖),2=列(横),3=层(前后)
>> 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
#reshape(A,n1,n2)-将矩阵改成n1xn2,注意元素个数要相同!
>> A = [1:3; 4:6]
A = 1 2 3
4 5 6
>> B=reshape(A,3,2)
B = 1 5
4 3
2 6
1.10 检查变量-isfunction
Name | Function | Name | Function |
---|---|---|---|
isinteger | Determine if input is integer array | ischar | Determine if input is character array |
islogical | Determine if input is logical array | isempty | Determine if input is empty array |
isnan | Detect an element that isnot a number (NaN) | isequal | Determine if arrays are numerically equal |
isnumeric | Determine if input is numeric array | isfloat | Determine if input is floating-point array |
isprime | Detect prime elements of array | isglobal | Determine if input is global variable |
isreal | Determine if all array elements are real numbers | ishandle | Detect valid graphics object handles |
iscell | Determine if input is cell array | isinf | Detect infinite elements of array |
-
档案存取
2.1 支持格式
内容 后缀 描述 读取 保存 Matlab 标准格式 mat 保存整个matlab的工作环境 load save Text文本 load save Spreadsheet表格 xls,xlsx 将数据保存为Excel xlsread xlswrite 2.2 Workspace读取与保存——save()& load()
#save()-将workspace data 以mat形式保存到当前目录文件下 >> a = magic(4); save mydata1.mat #该指令保存出来的数据为压缩格式 save mydata2.mat -ascii #-ascii可以保存具体数据 >> load('mydata1.mat') #读取数据,并且有变量名 load('mydata2.mat','-ascii') #读取数据,但是没有变量名 #保存某变量 >> save data.amt a b c #将工作空间中的 a b c 三个变量保存到data.mat中
2.3 Excel保存与读取——xlsread()& xlswrite()
>> score=xlsread('test.xlsx') #读取excel文件test,文件地址默认为当前目录下,只读取数值! >> score=xlsread('ltest.xlsx','B2:D4') #读取test中B2:D4区域的内容
#xlswrite读取 >> M=mean(score')'; #表格中一行为一个同学的成绩,mean计算列平均数,故先转置计算平均值再转置回去 xlswrite=('test.xlsx',M,1,'E2:E4'); #(filename,variable,sheet-第一个表单,location) xlswrite=('test.xlsx',{'Mean'},1,'E1'); #同上,写入标头Mean,格式为{'...'}
#利用xlsread完整读取数值和字符 >> [Score Header Raw]=xlsread('test.xlsx') #[数值 字符 全部]可从后向前依次省略 Score = 56 36 67 #[]第一个读取Excel的数值 34 56 77 43 45 67 Header = 4×4 cell 数组 #[]第二个读取Excel的字符串 {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} Raw = 4×4 cell 数组 #[]第三个读取Excel的所有数据,包括数值和字符 {[ NaN]} {'语文'} {'数学'} {'英语'} {'小明'} {[ 56]} {[ 36]} {[ 67]} {'小红'} {[ 34]} {[ 56]} {[ 77]} {'小李'} {[ 43]} {[ 45]} {[ 67]} #同样地,可以利用[]进行Excel的写入
2.4 文件I/O函数
Name Function fopen Open file, or obtain information about open files fclose Close one or all open files fscanf Read data from text file fprintf Write data to text file feof Test for end-of-file #fopen & fclose >> fid=fopen('[filename]','[permission]'); #permission-权限:'r','r+','w','w+','a','a+' >> fclose(fid);
#fscanf读取 A = fscanf(fid, format, size); #format为读取格式%f、%d、%g等,size为读取的个数
◼Example-将sin值写入文档
#1. 生成 x,y
#2. 打开一个文件
#3. 将 x,y 写入文件
#4. 关闭文件
>> x=0:pi/10:pi; #生产x和y
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 #打印文件内容
◼Example-文档读取
#1. 打开文档
#2. 检测文档是否到达结尾,循环读取
#3. 关闭文档
>> fid=fopen('asciiData.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',1);
i=i+1;
end
fclose(fid);