【问题标题】:Convert Cell to Struct in Matlab在 Matlab 中将单元格转换为结构体
【发布时间】:2017-07-20 21:14:47
【问题描述】:

我正在尝试访问具有 4 个结构的元胞数组的内容。

celldisp(tracks_array);

给出输出:

tracks_array{1} =
             kalmanFilter: [1×1 vision.KalmanFilter]
                       id: 0
        totalVisibleCount: 1
                     bbox: [390 171 70 39]
consecutiveInvisibleCount: 0
                      age: 1
tracks_array{2} =
             kalmanFilter: [1×1 vision.KalmanFilter]
                       id: 1
        totalVisibleCount: 1
                     bbox: [459 175 40 24]
consecutiveInvisibleCount: 0
                      age: 1
tracks_array{3} =
             kalmanFilter: [1×1 vision.KalmanFilter]
                       id: 2
        totalVisibleCount: 1
                     bbox: [220 156 159 91]
consecutiveInvisibleCount: 0
                      age: 1
tracks_array{4} =
             kalmanFilter: [1×1 vision.KalmanFilter]
                       id: 3
        totalVisibleCount: 1
                     bbox: [510 159 68 49]
consecutiveInvisibleCount: 0
                      age: 1

然后我使用 for 循环遍历元素..

for elmen = tracks_array
 structtt=cell2struct(elmen(1),{'id','bbox','kalmanFilter','age','totalVisibleCount','consecutiveInvisibleCount'},2);

这给出了错误

Error using cell2struct
Number of field names must match number of fields in new structure.

然后我在 for 循环中使用了这个

disp(elmen)
celldisp(elmen)

给予,

[1×1 struct]
 elmen{1} =
             kalmanFilter: [1×1 vision.KalmanFilter]
        totalVisibleCount: 1
                     bbox: [390 171 70 39]
 consecutiveInvisibleCount: 0
                       id: 0
                      age: 1

我想通过字段名称访问元素。我该怎么做?

现在,如果我尝试使用 getfield,则会出现此错误:

Struct contents reference from a non-struct array object.

【问题讨论】:

  • 您可以访问如下字段:disp(tracks_array{1}.kalmanFilter)

标签: matlab matlab-struct


【解决方案1】:

使用for 遍历元胞数组时,Matlab 中有一个奇怪的地方。您可能希望它在每次迭代中为您提供实际元素,但它为您提供了一个仅包含一个值的元胞数组,即该元素。但是使用elmen{1} 很容易提取实际元素。所以在你的代码示例中:

for elmen = tracks_array

    % The actual element is the first and only entry in the cell array
    structtt = elmen{1};

    % Display the structure
    disp(structtt);

    % Display a field within the structure
    disp(structtt.totalVisibleCount);

    % The same as above, but using getfield()
    disp(getfield(structtt, 'totalVisibleCount'));
end

您也可以将上述内容编写为元胞数组的 for 循环,使用 {} 语法提取每个元素

for index = 1 : length(tracks_array)
    structtt = tracks_array{index};

    % Display the structure
    disp(structtt);

    % Display a field within the structure
    disp(structtt.totalVisibleCount);

    % The same as above, but using getfield()
    disp(getfield(structtt, 'totalVisibleCount'));
end

【讨论】:

    猜你喜欢
    • 2014-01-14
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2021-04-22
    • 1970-01-01
    相关资源
    最近更新 更多