Chenming Zhang
Chenming Zhang

Reputation: 2566

vectorize data from struct in matlab

I have created a struct by:

a(1).x = {[1.1 5 8], [3 5 6]};
a(2).x = {[3.1 0 4], [9 8 7]};

and wish to obtain an array with value [1.1 3.1].

I have tried:

a.x{1}(1,1)
Field reference for multiple structure elements that is
followed by more reference blocks is an error.

Any ideas please?

Upvotes: 2

Views: 93

Answers (2)

user2271770
user2271770

Reputation:

The syntax error tells that you cannot further sub-reference inside multiple struct elements. So, the obvious one-liner—much slower than a for loop—that saves memory would be:

arrayfun(@(y) y.x{1}(1), a)

Just for you to compare performance, the loop-based version

function A = my_extractor(S)

        A = zeros(size(S));
        N = numel(S);

        for k = 1:N
                A(k) = S(k).x{1}(1);
        end;

end

Upvotes: 2

Dan
Dan

Reputation: 45752

If your .x field will always have the same dimensions then you could try

A = vertcat(a.x);
X = vertcat(A{:,1});
X(:,1)

Upvotes: 1

Related Questions