I have a structure, space_averaged_data, which has a member Ps that is defined as a cell array with a variable length. I assign values to this cell array after creating the structure as shown below (I've omitted the other structure fields for clarity):

Ps = cell( 1, num_p );for p = 1:length(Ps)Ps{p} = rand( 150, 1000 );endspace_averaged_data = struct( 'Ps', cell( 1, length(Ps) ) );for p = 1:length(Ps)space_averaged_data.Ps{p} = mean( Ps{p}, 2 );end

If the value of num_p is 1 (i.e., the cell array isn't an array), everything works just fine. If the value of num_p is greater than 1, however, I get the following error:

Scalar structure required for this assignment.Error in:space_averaged_data.Ps{p} = mean( Ps{p}, 2 );

What is the non-scalar structure in this assignment? I have no idea what the error is referring to.

1

Best Answer


You are creating a 1x5 struct array. To quote the struct documentation:

If value is a cell array, then s is a structure array with the same dimensions as value. Each element of s contains the corresponding element of value.

Since the second argument in the expression struct( 'Ps', cell( 1, length(Ps) ) ) is a 1x5 cell, the output struct will be a 1x5 struct array, and the proper assignment in the for-loop will be

space_averaged_data(p).Ps = mean( Ps{p}, 2 );

To get the behavior you desire, wrap the second argument in {} to make it a 1x1 cell array:

space_averaged_data = struct( 'Ps', {cell( 1, length(Ps) )} );

and the for-loop should work as expected.