6.1.5结构体中的数据处理

处理结构体中数据的最简单方法是在for循环(详见在结构体元素上循环). 类似的效果可以用structfun函数,其中用户定义的函数应用于结构体的每个字段。详见structfun.

或者,为了处理结构体中的数据,在处理之前,可能会将该结构体转换为另一种类型的容器。

 
: c = struct2cell (s)

从存储在结构体对象中的对象创建一个新的元胞数组。

如果f是结构体中的字段数,生成的cellarray将具有对应于的维度向量[f size(s)]例如

s = struct ("name", {"Peter", "Hannah", "Robert"},
           "age", {23, 16, 3});
c = struct2cell (s)
   ⇒ c = {2x1x3 Cell Array}
c(1,1,:)(:)
   ⇒
      {
        [1,1] = Peter
        [2,1] = Hannah
        [3,1] = Robert
      }
c(2,1,:)(:)
   ⇒
      {
        [1,1] = 23
        [2,1] = 16
        [3,1] = 3
      }

详见: cell2struct, namedargs2cell, fieldnames.

广告
 
: c = namedargs2cell (s)

从标量结构体创建字段键值对的元胞数组。

用例

s.Name = "Peter";
s.Height = 185;
s.Age = 42;

c = namedargs2cell (s)
  ⇒ { "Name", "Peter", "Height", 185, "Age", 42 }

详见: struct2cell.

广告

版权所有 © 2024-2025 Octave中文网

ICP备案/许可证号:黑ICP备2024030411号-2