From struct to cellarray - Matlab

39 Views Asked by At

I am working with wireless networks in Matlab. I have created the contact table, meaning the two nodes having contact and the starting and ending time of the contact. The contact table is in the form of a struct in Matlab as shown below:

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

Let's say this is the first entry of my contact table. Now I need to transform this entry to a cellarray which will have the following form:

45 CONN 23 76 up
58 CONN 23 76 down

or, to write it in a more general form:

t_start CONN node_1 node_2 up
t_end   CONN node_1 node_2 down

I need to be in this particular form in order to export them and use them to ONE simulator. So my question is how to transform this in Matlab? I understand that as many entries exist in the struct the cellarray will have the double size,for example for 50 entries there will be 100 rows in the cellarray, but I do not know how to do this.

1

There are 1 best solutions below

0
On BEST ANSWER

So you're going to want to use arrayfun to generate your data structure for each element. Then concatenate these together.

% 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{:})

So if in your example, we create two identical contacts just to test it.

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

We will get

data = 

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