I have a M x N sized structure array with fields var and val which are vectors.
What I would like to do is to get an M x N sized matrix A where each element A(i, j) contains the sum value of vector var (or val) from structure array
For example:
myStructure(1,5)
ans =
var: 1
val: [0.0100 0.1800 0.8100]
sum(myStructure(1,5).val)
ans =
1
myStructure(7,8)
ans =
var: [1 3]
val: [1x9 double]
myStructure(7,8).val
ans =
Columns 1 through 6
0.1111 0.1111 0.1111 0.1111 0.1111 0.1111
Columns 7 through 9
0.1111 0.1111 0.1111
Therefore A(1,5) should be 1 and the same way all elements A(i,j) should be equal to sum(myStructure(i,j).val).
Does anyone know how this could be done in Matlab without using for loops?
I’ve tried to use sum function in a number of ways (sum(messages.val) and sum(messages(:,:).val) …) but couldn’t get the desired result.
You can get the field elements into one matrix using:
If
valis always the same length (let’s name itP), this’ll be anumel(myStructure)*P x 1vector containing all values of all fields in sequence. You can reshape it of course back:and now just sum the first dimension, which leaves you the
MxNsizedAmatrix:squeeze is applied in this last step to remove the resulting singleton dimension (otherwise
Awould be of size1xMxN).If the
vallength can vary, I see no other way than looping it, or using arrayfun, which is essentially the same as looping: