Create struct from multiple arrays in a one-liner

2020-04-10 20:33发布

问题:

Let's say I have two arrays of the same size:

X = [1 2 3 4 ...]
Y = [1 2 3 4 ...]

But what I want is a struct:

S(1) =          S(2) = 
    X: 1            X: 2
    Y: 1            Y: 2

The obvious way to solve this is:

for ii = 1:length(X)
    S(ii).X = X(ii);
    S(ii).Y = Y(ii);
end

And you can even compress this to one line using arrayfun, but I am looking for a simpler one-liner. I was hoping for something along the lines of the this:

X = [S.X];

which solves the same problem but in the opposite direction.

Is it possible?

回答1:

use struct and cells

S = struct('X', num2cell(X), 'Y', num2cell(Y) );