从结构到元胞数组 - Matlab

From struct to cellarray - Matlab

我正在 Matlab 中处理无线网络。我创建了联系table,意思是有联系的两个节点和联系的起止时间。联系人table在Matlab中是结构体的形式如下图:

contact(1)
node_1:23
node_2:76
t_start: 45
t_end: 58

假设这是我联系人的第一个条目 table。现在我需要将此条目转换为 cellarray,它将具有以下形式:

45 CONN 23 76 up
58 CONN 23 76 down

或者,将其写成更一般的形式:

t_start CONN node_1 node_2 up
t_end   CONN node_1 node_2 down

我需要采用这种特殊形式才能导出它们并将它们用于一个模拟器。所以我的问题是如何在 Matlab 中转换它?我知道由于结构中存在许多条目,cellarray 将具有双倍大小,例如,对于 50 个条目,cellarray 中将有 100 行,但我不知道如何执行此操作。

因此您将要使用 arrayfun 为每个元素生成数据结构。然后将它们连接在一起。

% Anonymous function that creates a data structure for ONE struct entry
func = @(c){c.t_start, 'CONN', c.node_1, c.node_2, 'up'; ...
            c.t_end,   'CONN', c.node_1, c.node_2, 'down'};

% Now perform this on ALL struct elements and concatenate the result.
data = arrayfun(func, contact, 'uniform', 0); 
data = cat(1, data{:})

因此,如果在您的示例中,我们创建两个相同的 contacts 只是为了测试它。

contact = repmat(contact, [2, 1]);

我们会得到

data = 

    [45]    'CONN'    [23]    [76]    'up'  
    [58]    'CONN'    [23]    [76]    'down'
    [45]    'CONN'    [23]    [76]    'up'  
    [58]    'CONN'    [23]    [76]    'down'