结matlab结构体索引元素,Matlab-结构体数组的索引

本文详细介绍了MATLAB中结构体数组的索引、创建、连接及属性操作,包括1×n结构体数组、结构体数组连接、2×2结构体数组创建、结构体的初始化和内存管理,以及嵌套结构体的访问方法。通过实例展示了如何通过字段名和索引访问结构体元素,并探讨了结构体数组在内存中的存储方式和内存需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

%% 结构体数组的索引 (Structure Array)

% 注意:结构体的创建 与 矩阵/元胞数组 不同,元胞数组以元胞的方式进行储存,而结构体是以 fields 储存的(而不是以对象个数储存的)

% 所以元胞数组创建时,提供元胞的大小,而结构体的创建

%% 1.n * 1 的结构体数组

imname = dir(['C:\Users\ncf\Desktop\' '*.doc'])

imname.name % 返回所有的 name ,name 相当于一个结构体的变量,一个属性(注意这个和 cell 的联系)

imname(:).name %返回所有的 name

imname(1).name % 返回第一个对象的 name

imname(1) % 返回第一个对象的所有属性2

%% 2.使用 [] 连接结构体数组

% To concatenate structures, they must have the same set of fields,

% but the fields do not need to contain the same sizes or types of data.

% 前提结构体必须要有相同 set of fields 属性集,但是对于某一个属性不需要包含相同大小和类型的数据

struct1.a = 'first';

struct1.b = [1,2,3];

struct2.a = 'second';

struct2.b = rand(5);

combined = [struct1, struct2] % combined 为 1*2 的 struct

%% 3.create a 2-by-2 struct array 创建一个 2*2 的结构体数组

new(1,1).a = 1;

new(1,1).b = 10;

new(1,2).a = 2;

new(1,2).b = 20;

new(2,1).a = 3;

new(2,1).b = 30;

new(2,2).a = 4;

new(2,2).b = 40;

% 理解 a b 相当于结构体的属性,每一个对象都有 a b 属性

% 而对象的索引就是 new(2,2) :第四个对象,第二行第二列的对象,这种可以理解成将矩阵一样,实际不是以二维储存的,而是 new(3)

% 将二维转成列

larger = [combined; new] % 因为 combined new 都含有 a b 属性则可以合并

% [] 可以连接矩阵也可以连接结构体

% [ ; ] 竖直连接 相当于函数 vertcat

% [ ] 水平连接 相当于函数 horzcat

% % % % n * n 结构体的初始化和创建 (与矩阵,元胞数组的初始化不同)

newStruct(1:25,1:50) = struct('a',ones(20),'b',zeros(30),'c',rand(40)); % 指定初始化值

% or

newStruct(1:25,1:50).a = ones(20); % 指定初始化值

newStruct(1:25,1:50).b = zeros(30);

newStruct(1:25,1:50).c = rand(40);

% or

newStruct(1:25,1:50).a = []; % 不指定初始化值

newStruct(1:25,1:50).b = [];

newStruct(1:25,1:50).c = [];

% or

newStruct(1:25,1:50) = struct('a',[],'b',[],'c',[]); % 不指定初始化值

%% 4.结构体的储存方式

% A structure is a data type that groups related data using data containers called fields.

% Each field can contain data of any type or size.

% 结构体使用 fields 这样的数据容器将 结构体与数据联系在一起,每一个 field 可以包含不同大小数据类型的数据

%% 5.结构体数组(由每一个结构体组成(即对象),每一个结构体(对象)有相同的属性集(名字和数量相同) fields,不同结构体里的相同属性值,数据类型/大小可以不同)

% /1.All structs in the array have the same number of fields

% /2.All structs have the same field names

% /3.Fields of the same name in different structs can contain different types or sizes of data.

patient(1).name = 'John Doe';

patient(1).billing = 127.00;

patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];

patient(3).name = 'New Name';

patient(3)

% 对于 patient(3) 对象的 billing test 未指定时为空

%% 6.Comma-Separated Lists

% 1.Comma-Separated List

% Typing in a series of numbers separated by commas gives you what is called a comma-separated list

1,2,3 % 用,分开

% 2.Generating a Comma-Separated List:

% 2/1.Generating a List from a Cell Array (由元胞数组产生)

C = cell(4,6);

for k = 1:24

C{k} = k*2;

end

C

C{:,5} % extracting the fifth column generates the following comma-separated lis

% C{1,5},C{2,5},C{3,5},C{4,5} 上面的那个相当于这个

% 2/2.Generating a List from a Structure (由结构数组生成)

S = cell2struct(C,{'f1','f2','f3','f4','f5','f6'},2);

S.f5

% S(1).f5,S(2).f5,S(3).f5,S(4).f5 上面的与这个相同

% 2/3.Assigning Output from a Comma-Separated List (指定输出)

C = cell(4,6);

for k = 1:24

C{k} = k*2;

end

[c1,c2,c3,c4,c5,c6] = C{1,1:6};

c5

% 2/3/1.对于指定少的输出时,舍弃其他的,对于结构体也一样

% You also can use the deal function for this purpose 也可以使用函数 deal

[c1,c2,c3] = C{1,1:6}

S = cell2struct(C,{'f1','f2','f3','f4','f5','f6'},2);

[sf1,sf2,sf3] = S.f5;

sf3

% 3.使用 Comma-Separated Lists

% 3/1.Constructing Arrays (重建数组)

% When you specify a list of elements with C{:, 5},

% MATLAB inserts the four individual elements

A = {'Hello',C{:,5},magic(4)}

% 3/2.Displaying Arrays (显示数组0)

% Use a list to display all or part of a structure or cell array

A{:}

% 3/3.Concatenation (合并)

% 提取出数据再合并

A = [C{:,5:6}]

% 3/4.Function Call Arguments (作为函数的输入)

X = -pi:pi/10:pi;

Y = tan(sin(X)) - sin(tan(X));

C = cell(2,3);

C{1,1} = 'LineWidth';

C{2,1} = 2;

C{1,2} = 'MarkerEdgeColor';

C{2,2} = 'k';

C{1,3} = 'MarkerFaceColor';

C{2,3} = 'g';

figure

plot(X,Y,'--rs',C{:})

% 3/5.Function Return Values (函数返回值)

% These values are returned in a list with each value separated by a comma

% Instead of listing each return value, you can use a comma-separated list with a structure or cell array

% 函数的返回值在返回时,是有逗号隔开的,可以用 a comma-separated list with a structure or cell

% array 代替列出每一个返回值

C = cell(1,3);

[C{:}] = fileparts('work/mytests/strArrays.mat')

%% 7.Access Elements of a Nonscalar Struct Array (从结构数组中获取元素,与之前的内容有交集)

% 1.access data from multiple elements of a nonscalar structure array (获取数据)

s(1).f = 1;

s(2).f = 'two';

s(3).f = 3 * ones(3);

s(1:3).f

% or

s.f

% MATLAB? returns the data from the elements in a comma-separated list,

% 你不能指定这个 list 到 一个变量中 syntax v = s.f (错,这个默认获取第一个数据,舍弃后两个)

% 可以采取以下两种方式:

[v1, v2, v3] = s.f % 指定 list 到等个数的变量中

c = {s.f}; % 指定 list 到元胞数组中

% 2.process data from multiple elements of a nonscalar structure array (处理数据)

% 如果你想对数组中的每一个元素(具体到每一个结构体的某一属性的元素)施以相同处理,使用 arrayfun 函数

numElements = arrayfun(@(x) numel(x.f), s)

% 数出每一个结构体中的 f 属性元素数目,相当于下面的表达式(这样可以扩展函数的使用范围,使输入的可以是很多类型的数据)

[numel(s(1).f) numel(s(2).f) numel(s(2).f)]

%% 8.Ways to Organize Data in Structure Arrays (组织数据的方法)

% 1.Plane Organization

img.red = RED;

img.green = GREEN;

img.blue = BLUE;

adjustedRed = .9 * img.red; % 对某一属性的面操作

% 2.Element-by-Element Organization

patient(1).name = 'John Doe';

patient(1).billing = 127.00;

patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205]; % 对某一对象操作

%% 9.Memory Requirements for a Structure Array (结构体的内存分配)

% Structure arrays do not require completely contiguous memory.

% However, each field requires contiguous memory,

% as does the header that MATLAB? creates to describe the array.

% For very large arrays, incrementally increasing the number of fields or the number of elements in a field results in Out of Memory errors.

% However, in this case, MATLAB only allocates memory for the header, and not for the contents of the array.

% matlab 只为 field(the header) 分配内存,而不是为数组中的内容

% Structure arrays 不需要连续的内存,但是每一个 field 需要连续的内存

%% 10.Access Data in Nested Structures (嵌套结构体)

% syntax :

% structName(index).nestedStructName(index).fieldName(indices)

% structName(index) 是最大的类 ,nestedStructName(index)

% 是较小的类(生成对象),fieldName(indices) 这个索引的是具体结构体的属性的内容

s.n.a = ones(3);

s.n.b = eye(4);

s.n.c = magic(5);

s(1).n(2).a = 2*ones(3);

s(1).n(2).b = 2*eye(4);

s(1).n(2).c = 2*magic(5);

s(2).n(1).a = '1a';

s(2).n(2).a = '2a';

s(2).n(1).b = '1b';

s(2).n(2).b = '2b';

s(2).n(1).c = '1c';

s(2).n(2).c = '2c';

% s(2).n(2).c :s 的第二个类下的 n 类的 第二个对象的 c 属性

% Access part of the array in field b of the second element in n within the first element of s:

part_two_eye = s(1).n(2).b(1:2,1:2)

### MATLAB 结构体索引方法 在 MATLAB 中,结构体是一种灵活的数据类型,能够将多种不同类型的变量组合到一起。为了访问和操作结构体中的数据,可以通过索引实现对单个字段或整个结构体数组的操作。 #### 访问单一结构体的字段 对于单独的一个结构体,可以直接使用点运算符 `.` 来访问其中的字段。例如: ```matlab % 定义一个简单的结构体 person.name = 'Alice'; person.age = 30; person.city = 'New York'; % 使用点运算符访问字段 disp(person.name); % 输出 Alice disp(person.age); % 输出 30 ``` 上述代码展示了如何定义一个名为 `person` 的简单结构体以及如何通过点运算符访问其字段[^3]。 --- #### 索引结构体数组 当处理的是结构体数组时,可以索引与点运算符来访问特定位置上的结构体及其字段。例如: ```matlab % 创建一个包含两个元素结构体数组 people(1).name = 'Alice'; people(1).age = 30; people(1).city = 'New York'; people(2).name = 'Bob'; people(2).age = 25; people(2).city = 'Los Angeles'; % 使用索引来访问第一个结构体的字段 disp(people(1).name); % 输出 Alice % 使用索引来访问第二个结构体的字段 disp(people(2).city); % 输出 Los Angeles ``` 这里展示了一个长度为 2 的结构体数组 `people`,并通过 `(index)` 和 `.field_name` 组合的方式访问指定位置上结构体的字段[^1]。 --- #### 遍历结构体数组 如果需要逐一遍历结构体数组并对每个元素执行某些操作,则可以利用循环完成此任务。例如: ```matlab for i = 1:length(people) fprintf('Name: %s, Age: %d, City: %s\n', ... people(i).name, people(i).age, people(i).city); end ``` 这段代码会依次打印出结构体数组中每个人的姓名、年龄和城市信息。 --- #### 复杂情况下的索引:嵌套结构体 有时可能会遇到更复杂的场景——即某个字段本身也是一个结构体或者数组。此时仍然可以用类似的逻辑来进行多层索引。比如下面的例子说明了如何处理这种情形: ```matlab data.person.info.height = [170; 180]; data.person.info.weight = [60; 75]; % 获取第一个人的高度 firstHeight = data.person.info.height(1); % 打印果 fprintf('First person height is %.f cm.\n', firstHeight); ``` 在这个例子中,`info` 是另一个层次更深的子结构体,而它的成员又是向量形式存储的信息;因此最终还需要加上额外的一维下标才能精确提取目标值。 --- #### 特殊应用案例分析 (Stateflow 结构体索引) 针对像 Stateflow 这样的高级功能模块所使用的复杂自定义类型对象(如 SubBus),则可能涉及到更加细致化的映射关系转换过程。具体来说就是先解析源端传入参数里的各个分项内容再重组为目标格式输出回去的过程描述如下所示: 假设存在这样一个函数 sb2abc ,它接受一种特殊的 subbus 类型作为输入参数,并将其内部 ele 字段拆解成三部分重新组装进一个新的局部临时变量 y 当做中间过渡载体之后才正式赋予外部可见的果变量 y 。那么实际编码实现大致应该是这样的样子 : ```matlab function y = sb2abc(subbusInput) y.ele.vectorPart = subbusInput.ele(1:end-4); % 提取矢量部分 y.ele.matrixPart = reshape(subbusInput.ele(end-3:end),3,2); % 转置矩阵片段 y.ele.scalarValue = subbusInput.ele(end); % 单独获取最后一个数代表纯数量级意义 end ``` 以上程序片段清楚地体现了从原始复合实体里分离各构成要素直至最后封装回统一标准接口这一整套流程步骤[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值