Matlab(科伊恩)学习3——变量与档案存取

三、变量与档案存取

  1. 变量

    1.1 变量类型

    类型
    logical逻辑类型
    char字符型
    numericint、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 常用结构体函数

    NameFunctionNameFunction
    cell2struct元胞数组→结构体数组rmfield(struct,x)移除struct里的x元素
    fieldnames(struct)结构体元素setfield
    getfieldstruct
    isfieldstruct2cell结构体数组→元胞数组
    isstructstructfun
    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 常用单元数组函数

    NameFunctionNameFunction
    cell创建cellcellstrCreate cell array of strings from character array
    cell2matcell array→numeric arrayiscell判断是否为cell array
    cell2structcell array→struct arraymat2cellConvert array to cell array with different sized cells
    celldispnum2cellConvert array to cell array with consistently sized cells
    cellfunApply function to each cell in cell arraystruct2cellConvert structure to cell array
    cellplotGraphically 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

NameFunctionNameFunction
isintegerDetermine if input is integer arrayischarDetermine if input is character array
islogicalDetermine if input is logical arrayisemptyDetermine if input is empty array
isnanDetect an element that isnot a number (NaN)isequalDetermine if arrays are numerically equal
isnumericDetermine if input is numeric arrayisfloatDetermine if input is floating-point array
isprimeDetect prime elements of arrayisglobalDetermine if input is global variable
isrealDetermine if all array elements are real numbersishandleDetect valid graphics object handles
iscellDetermine if input is cell arrayisinfDetect infinite elements of array
  1. 档案存取

    2.1 支持格式

    内容后缀描述读取保存
    Matlab 标准格式mat保存整个matlab的工作环境loadsave
    Text文本loadsave
    Spreadsheet表格xls,xlsx将数据保存为Excelxlsreadxlswrite

    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函数

    NameFunction
    fopenOpen file, or obtain information about open files
    fcloseClose one or all open files
    fscanfRead data from text file
    fprintfWrite data to text file
    feofTest 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);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值