Search code examples
arraysmatlabvectormatlab-struct

Matlab struct of vectors to vector of struct conversion


How can I convert arrays x(1:N), y(1:N) into a structure S(1:N) with fields .x and .y in a fast way without for-loop? I can easily convert x, y into a struct of arrays:

S.x = x; S.y = y;

Since I need to work with individual sets of (xi, yi), how can I convert this to an array of struct? I have found a solution to do this via table type, but I don't like this solution:

S = table2struct(struct2table(S))

Solution

  • You should just use struct directly after first converting x and y to cell arrays. When the values passed to struct are cell arrays, then this results in a multi-element struct with the same dimensions as that cell array.

    S = struct('x', num2cell(x), 'y', num2cell(y));