-
Notifications
You must be signed in to change notification settings - Fork 0
/
matlab_04.m
43 lines (33 loc) · 1.44 KB
/
matlab_04.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
%% MATLAB 结构体对象和单元对象
% 一个结构体变量由若干相关数据组成
% 存放各个数据的容器称为字段
% 访问方式:圆点表示法,即"结构体变量.字段"
% 创建学生的结构体
stu.num = 101;
stu.name = '世界第一大帅哥';
stu.age = 114514;
% 结构体的字段也可以是结构体
stu.score.math = 95;
stu.score.physics = 88;
% 一个结构体只能存储一个对象的信息
% 如果想存储多个对象的信息,可以使用结构体数组
% 调用格式:s = struct(field1, value1, field2, value2, ……, fieldN, valueN)
% 其中field是字段名,value是字段值
% 样例:
f1 = 'num'; v1 = {2001, 2002, 2004};
f2 = 'name'; v2 = {'小明', '小强', '小红'};
f3 = 'age'; v3 = {114514, 1919810, 23333};
f4 = 'score'; v4 = {[100, 90], [27, 80], [85, 95]};
students = struct(f1, v1, f2, v2, f3, v3, f4, v4);
% 结构体的引用:小括号+序号
score1 = students(1).score;
stu3 = stuedents(3);
% 使用rmfield函数删除字段
% stu = rmfield(stu, 'num');
% 单元数组,又称元胞数组:把不同类型的数据组合成一个整体
% 创建单元数组时,数据用大括号括起来
C1 = {1, [1, 2; 3, 4], 3; 'text', pi, {11; 22; 33}};
% 也可以用cell函数创建空的单元数组,再给里面的元素赋值
C2 = cell(2, 3);
C2{1, 1} = 1; C2{1, 2} = [1, 2; 3, 4]; C2{1, 3} = 3;
C2{2, 1} = 'text'; C2{2, 2} = pi; C2{2, 3} = {11; 22; 33};