Matlab笔记 |
您所在的位置:网站首页 › 结构体变量什么意思 › Matlab笔记 |
一、结构数组的基本使用
结构体的定义即为C语言中结构体的初始化,其引用成员(在Matlab中为field,字段的意思)和C语言相同。 1、直接赋值 >> student(1).name='Silen'; student(1).id=1234; student(1).grade=[1 2 3;4 5 6;7 8 9]; student(1).grade(2,2) %输出成绩5 ans = 5需要注意的是,进行赋值时需要对结构体做标量,即做标记,要不然就会出现下面这种情况,出现报错 >> student.grade=[2 3 4;5 6 7;8 9 0]; 此赋值需要标量结构体。 2、用struct函数定义 >> A=[1 2 3 4]; >> B=struct('id',12324,'grade',A) B = 包含以下字段的 struct: id: 12324 grade: [1 2 3 4] 二、相关结构数组函数1、fieldnames:展示结构体所有字段名 >> fieldnames(student) ans = 5×1 cell 数组 {'you' } {'id' } {'gread'} {'name' } {'grade'}2、getfield:得到结构体的相应字段 >> c=getfield(student,'id'); >> c c = 12343、isfield:判断字段是否是结构体内的字段 >> c=isfield(student,'ok') c = logical 0 >> c=isfield(student,'id') c = logical 14、isstruct:判断是否是结构体类型 >> A=struct('id',4567,'grade',[1 2 3;4 5 6;7 8 9]); >> B=[1 2 3 4]; >> C=isstruct(A) C = logical 15、orderfields:对结构体的fields按字母顺序排序 >> A=struct('c',1234,'a',34,'b',56); >> orderfields(A) ans = 包含以下字段的 struct: a: 34 b: 56 c: 12346、rmfield:remove结构体中的field >> rmfield(A,'a') ans = 包含以下字段的 struct: c: 1234 b: 567、setfield:用于更新结构体字段 >> setfield(A,'a',78) ans = 包含以下字段的 struct: c: 1234 a: 78 b: 56 三、嵌套结构数组 >> A=struct('a',1234,'b',2345,'B',struct('c',5678,'d',6789)) A = 包含以下字段的 struct: a: 1234 b: 2345 B: [1×1 struct] >> A.B.d ans = 6789 四、元胞数组元胞数组即是将成员数据按矩阵形式排列,数据部分用{}或者位置部分用{}都可 >> A(1,1)={[1 2 3;4 5 6]}; >> A(1,2)={'hello'}; >> A(2,1)={'world'}; >> A(2,2)={[2 3 4;5 6 7]}; >> A A = 2×2 cell 数组 {2×3 double} {'hello' } {'world' } {2×3 double}那么如何查看cell arry中的数据呢 >> A(1,1) ans = 1×1 cell 数组 {2×3 double} >> A{1,1} ans = 1 2 3 4 5 6可以看到,使用(1,1)只能看到数据类型,而用{1,1}才能展开数据 五、矩阵转换成元胞数组1、使用num2cell函数 >> a=magic(3); >> b=num2cell(a) b = 3×3 cell 数组 {[8]} {[1]} {[6]} {[3]} {[5]} {[7]} {[4]} {[9]} {[2]}magic(n)函数的作用是生成一个n*n的矩阵,矩阵元素是由整数1到n^2组成的并且任何行任何列的和都相等,阶数n必须是大于等于3的标量 2、使用mat2cell函数 C = mat2cell(A,dim1Dist,...,dimNDist)mat3cell可将原矩阵沿维度划分为各个子数组,并共同组成一个元胞数组 >> c=mat2cell(a,[1 1 1],[1 2]) c = 3×2 cell 数组 {[8]} {[1 6]} {[3]} {[5 7]} {[4]} {[9 2]} 六、多维数组多维数组是在row和column的基础上再加维度 1、使用cat(n,A,B)函数 >> A=[1 2;3 4]; B=[5 6;7 8]; C=cat(1,A,B); D=cat(2,A,B); E=cat(3,A,B); >> disp(C); 1 2 3 4 5 6 7 8 >> disp(D) 1 2 5 6 3 4 7 8 >> disp(E) (:,:,1) = 1 2 3 4 (:,:,2) = 5 6 7 82、使用reshape(D,n,n,n)函数 >> reshape(D,2,2,2) ans(:,:,1) = 1 2 3 4 ans(:,:,2) = 5 6 7 8对于reshape函数再提一句,它对矩阵做reshape的顺序是从row到column >> F=[1 2 3;4 5 6]; >> f1=reshape(F,3,2) f1 = 1 5 4 3 2 6 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |