20421

# Do I always need to use a cell array to assign multiple values to a struct array?

I've got a nested struct array like

```A(1).B(1).var1 = 1; A(1).B(2).var1 = 2; ```

Now I want to change the values of `var1` to using the elements of the vector `x = [3; 4]` for each of the respective values.

The result should be

```A(1).B(1).var1 = 3; A(1).B(2).var1 = 4; ```

I have tried

```% Error : Scalar structure required for this assignment. A(1).B.var1 = x; % Error : Insufficient number of outputs from right hand side of equal sign to satisfy assignment. [A(1).B.var1] = x(:); ```

Curiously, if x is a cell array, the second syntax works

```x = {3, 4}; [A(1).B.var1] = x{:}; ```

Luckily, it's not too complicated to convert my numeric vector to a cell array using `mat2cell`, but is that the only way to do this assignment without a for loop?

What's the correct syntax for multiple assignment to a nested struct array? Can I use numeric vectors or do I have to use cell arrays?

The statement

```[A(1).B.var1] = x{:}; ```

is shorthand for

```[A(1).B.var1] = deal(x{:}); ```

(see the documentation for `deal`).

Thus you can also write

```[A(1).B.var1] = deal(3,4); ```

I'm not aware of any other way to assign different values to a field in a struct array in a single command.

If your values are in a numeric array, you can easily convert it to a cell array using `num2cell` (which is simpler than the `mat2cell` you found).

```data = [3,4]; tmp = num2cell(data); [A(1).B.var1] = tmp{:}; ```

In general, struct arrays are rather awkward to use for cases like this. If you can, I would recommend that you store your data in normal numeric arrays, which make it easier to manipulate many elements at the same time. If you insist on using a struct array (which is convenient for certain situations), simply use a for loop:

```data = [3,4]; for ii = 1:length(A(1).B) A(1).B(ii).var1 = data(ii); end ```

The other alternative is to use `table`.