Jim
Jim

Reputation: 5960

"Reverse" of arrayfun

I have an array of "object" structures, OBJECT_ARRAY, that I must often transform into individual arrays for each element of the object structures. This can be done using arrayfun. It's more tedious than simply refereeing to OBJECT_ARRAY(k).item1, but that's how The Mathworks chose to do it.

In this case today, I have used those individual arrays and calculated a corresponding derived value, newItem, for each element and I need to add this to the original array of structures. So I have an array of newItems.

Is there a straightforward way to do an assignment for each object in OBJECT_ARRAY so that (effectively) OBJECT_ARRAY(k).newItem = newItems(k) for every index k?

I am using version 2015a.

Upvotes: 1

Views: 71

Answers (1)

Suever
Suever

Reputation: 65460

You shouldn't need arrayfun for any of this.

To get values out, you can simply rely on the fact that the dot indexing of a non-scalar struct or object yields a comma-separated list. If we surround it with [] it will horizontally concatenate all of the values into an array.

array_of_values = [OBJECT_ARRAY.item1];

Or if they are all different sizes that can't be concatenated, use a cell array

array_of_values = {OBJECT_ARRAY.item1};

To do assignment, you can again use the comma separated list on the left and right side of the assignment. We first stick the new values in a cell array so that we can automatically convert them to a comma-separated list using {:}.

items = num2cell(newitems);
[OBJECT_ARRAY.item1] = items{:};

Upvotes: 5

Related Questions