embert
embert

Reputation: 7602

Data from array struct in corresponding shape

Say, we have an array of structs

data = struct('position',[]);

data(1,1).position = 11;
data(1,2).position = 12;
data(2,1).position = 21;
data(2,2).position = 22;

I learned that to get the entries from a field from all structs in the array, we can use

>> [data.position]

ans =

    11    21    12    22

But this gives the data in a row. How can we get it in the original shape of the array, without looping the array in MCode?

Desired output:

position =

    11    12
    21    22

Upvotes: 2

Views: 75

Answers (2)

Divakar
Divakar

Reputation: 221684

If you are working with empty entries, you can use struct2cell to convert the struct data into cell array that enables us to store empty entries as empty cells -

data_cell = permute(struct2cell(data),[2 3 1])

out  = data_cell(:,:,strcmp(fieldnames(data),'position'))

So, if you have something like this with the (2,2) missing -

data = struct('position',[]);
data(1,1).position = 11;
data(1,2).position = 12;
data(2,1).position = 21;

You would have -

out = 
    [11]    [12]
    [21]      []

Based on @CitizenInsane's nice observation and which might be very close to @rayryeng's answer, but one that deals with cell arrays instead of numeric arrays, would be this -

out = reshape({data.position}, size(data))

Upvotes: 2

rayryeng
rayryeng

Reputation: 104555

Use reshape. This will restructure an input vector / matrix into another vector / matrix of a desired shape. Specifically, you can specify the dimensions of data into reshape as well as the row vector produced by [data.position] and it'll reshape the vector with the right dimensions for you.

data = struct('position',[]);

data(1,1).position = 11;
data(1,2).position = 12;
data(2,1).position = 21;
data(2,2).position = 22;

position = reshape([data.position], size(data))

position =

    11    12
    21    22

Note that the elements are shaped in column-major format so the values are stacked column-wise. As you can see, the first two elements become the first column of the output matrix, while the last two elements become the second column of the output matrix.

Upvotes: 3

Related Questions