Tulkkas
Tulkkas

Reputation: 1013

Extracting field from cell array of structure in matlab

I have a cell array (let's say size 10) where each cell is a structure with the same fields. Let's say they all have a field name x.

Is there a way to retreive in a vector the value of the field x for all the structure in the cell array? I would expect the function to return a vector of size 10 with in position 1, the value of the field x of the structure in cell 1 etc etc...

EDIT 1:

The structure in the cell array have 1 field which is the same for all but some others which are different.

Upvotes: 0

Views: 2773

Answers (3)

kwrush
kwrush

Reputation: 171

Let's say you have

c = {s1, s2, s3, ...., sn};

where common field is 'field_1', then you have two options

Use cell2mat.

cc = cell2mat(c); % which converts your cell array of structs into an array of structs

value = [cc.field_1]; % if values are number

or

value = {cc.field_1}; % if values are characters, for example

Another option is to use cellfun.

If the field values are characters, you should set "UniformOutput" to "false"

value = cellfun(@(x) x.field_1, c, 'UniformOutput', false)

The first option is better. Also, try to avoid using cell/cellfun/arrayfun whenever you can, vectors are way faster and even a plain for loop is more effecient

Upvotes: 0

Tom
Tom

Reputation: 445

The below code creates a cell array of structures, and extracts field 'x' of each structure to a vector v.

%create a cell array of structures
s1.a = 'hello';
s1.x = 1;
s2.a = 'world';
s2.x = 2;
c{1} = s1;
c{2} = s2;
v = zeros(1,2);

%extract to vector
for idx=1:size(c,2)
    v(1,idx) = c{idx}.x;
end

Upvotes: 1

MikeLimaOscar
MikeLimaOscar

Reputation: 233

First convert your cell array of structures, c, (with identical field names in the same order) to a structure array:

c = cell2mat(c)

Then, depending on the data types and sizes of the elements of the field, you may be able to use

[c.x]

to extract your vector of field x values in the "standard" way.

It is also possible that you can skip the conversion step and use cellfun(@(e)e.x, c) to do the extraction in one go.

Upvotes: 2

Related Questions