Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33944

Create struct from multiple arrays in a one-liner

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?

Upvotes: 3

Views: 146

Answers (1)

Shai
Shai

Reputation: 114966

use struct and cells

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

Upvotes: 6

Related Questions