0

how do I extract an array of object properties from an object array (where each of the objects within that array has that property?)

Ex.:

classdef myClass
    properties
        myProperty = 1
    end
end

--

myObjectMatrix(1:1000)  = myClass()
myObjectMatrix(100:234).myProperty   % what I thought would work but results in lots of individual results

[myObjectMatrix(100:234)..myProperty] works, but only in one dimension. I need to use reshape() if I have more than one dimension to 'fold' my results back.

Is there a better way?

Thanks!

1 Answer 1

2

Basically that code would act on each member in turn and return a separate answer, so in the end you only get a 1x1 output.

The solution in that example is to use arrayfun(), such as:

myObjectMatrix(1:1000)  = myClass()
output = arrayfun(@(x) x.myProperty,myObjectMatrix(100:234))

That would give you a 1x135 array containing the value of each of the myProperty member from each of the elements selected from the class array.

In arrayfun you give a function to perform on each element in the array and then the array to act on. In this case I created an anonymous function which simply accesses myProperty on x - where x will be each object in the array in turn.


It is important to note that the above will only work if the property is a single value, not a matrix/array. If it is an array then the output will be nonuniform, and you will have to do:

output = arrayfun(@(x) x.myProperty,myObjectMatrix(100:234),'UniformOutput', false)

In this case 'output' will be a cell array containing the value of the property of each class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.