Jim
Jim

Reputation: 5960

Matlab arrayfun with array of elements that are [1x4 struct]

I have a array, 'MY_STRUCTURES_Array', with single row and N columns. Each element is a [1x4 struct]. I want to extract a numeric valued 'thisField' from each structure of each [1x4 struct] element.

The result I am looking for is a 4xN array of the values for each 'thisField' value, where each row in this result corresponds to a colum in the [1x4 struct].

The code I am using is this:

arrayfun(@(x) (x.thisField),   MY_STRUCTURES_Array);

Matlab returns the error

Attempt to reference field of non-structure array.

If I put the following in the command line,

MY_STRUCTURES_Array{1}

I get a list of all of the fields of the [1x4 struct].

If I put this in the command line,

MY_STRUCTURES_Array{1}.thisField

I get four answers, like this:

ans =

       1


ans =

       1


ans =

       1


ans =

       0

If I look at the size

size(MY_STRUCTURES_Array{1}.thisField)

Matlab says "Error using size", so I see this is not an array. But I'm not sure what it is.

I am not sure how to proceed to get the 4xN array I am looking for.

UPDATE

Output from command MY_STRUCTURES_Array returns a row array of [1x4 struct].

Output from whos MY_STRUCTURES_Array{1} returns nothing

Output from whos MY_STRUCTURES_Array returns:

 Name                     Size               Bytes  Class    Attributes

 MY_STRUCTURES_Array      1x103            1371136  cell      

Output from whos MY_STRUCTURES_Array{1}.thisField returns nothing

Output from MY_STRUCTURES_Array{1}.thisField was shown in the original post.

Upvotes: 1

Views: 398

Answers (1)

user20160
user20160

Reputation: 1394

The fact that you're accessing MY_STRUCTURES_Array as MY_STRUCTURES_Array{1} indicates that it's a cell array, so I'll answer based on that.

Say we have MY_STRUCTURES_Array as a cell array of struct arrays:

MY_STRUCTURES_Array = {[1x4 struct], [1x4 struct], [1x4 struct]}

It contains N elements (here N = 3). Each element is a struct array with 4 elements and various fields. We want to extract the value of field foo, which contains a single number.

out = zeros(4, N);

for it = 1 : N
    out(:, it) = [MY_STRUCTURES_Array{it}.foo];
end

out(i, j) now contains the value of MY_STRUCTURES_Array{j}(i).foo

EDIT:

Using arrayfun():

out = arrayfun(@(x) x.foo, cell2mat(MY_STRUCTURES_Array')')

This converts the cell array of struct arrays into a 2d struct array, then extracts field foo from each element.

Upvotes: 1

Related Questions