在Matlab中将Cell转换为Struct

时间:2017-07-20 05:53:31

标签: matlab matlab-struct

我试图访问具有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.

1 个答案:

答案 0 :(得分:0)

使用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
相关问题