1

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.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Jim
  • 5,940
  • 9
  • 44
  • 91
  • 1
    Possible duplicate of [Updating one field in every element of a Matlab struct array](http://stackoverflow.com/questions/9303070/updating-one-field-in-every-element-of-a-matlab-struct-array) – beaker Sep 20 '16 at 18:50
  • I had voted to close as a dupe, but @Suever added a more complete answer while I was marking it. Removing dupe vote. – beaker Sep 20 '16 at 18:54
  • 1
    Please refrain from using a plethora of markdown styles for (pseudo-)code, but use the designated code markdown for that. That way people actually understand what is code and what is not. – Adriaan Sep 20 '16 at 18:55

1 Answers1

5

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{:};
Suever
  • 64,497
  • 14
  • 82
  • 101