File Exchange

image thumbnail

Convert from a structure of arrays into an array of structures

version 1.0 (1.49 KB) by

converts from a structure, where each field contains an Nx1 array, into an 1xN array of structures



View License

Converts from a structure, where each field contains an Nx1 array, into an 1xN array of structures, where each field contains 1 value.

I decided to create and share this after not finding a readily available answer on the internet; though I suspect SOMEONE out there has already solved this issue.

S = structofarrays2arrayofstructs(A) assumes that A is a struct, with each field
containing Nx1 (columns) of values. (theoretically NxM values, where M may vary). This results in an Nx1 array of
structs, each containing 1 (or M) values.

>> A.flower={'Daisy';'Rose';'Violet'};
>> A.color={'white';'red';'violet'};

>> S = structofarrays2arrayofstructs(A)

S =
1x3 struct array with fields:

>> S(2)
ans =
flower: 'Rose'
color: 'red'

Note, Any cells it encounters are unwrapped.

In a test, with 6 fields, each with 377670x1 values (mixed, Cells of chars and arrays of Double), it took ~20 seconds to convert.

Comments and Ratings (1)

Jan Berling

Thanks for this helpful function! With column based (1xN) arrays it doesn't work, because of exceeded matrix dimensions. (The number of elements is taken from the input arrays, not the number of rows.)
For my needs I have changed it to work with Column based (1xN) arrays.
Could be useful to add a flag which lets users choose row or column based arrays.

MATLAB Release
MATLAB 7.13 (R2011b)

Inspired: soa2aos(IN, LCHK)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video