MATLAB: Adding the elements of a field of a struct


Hello Matlabgeeks, I am trying to add the elements of a field of a struct array using the following syntax:
totaldistancecovered = sum([output.distanceininches]);
and the following is the syntax that I applied to create the field in the struct:
output(activityNum).distanceininches = zDistance(startind:endind);
output is my struct and distanceininches is my field. However, when I use the former syntax to add the elements it is throwing an error:
Error using horzcat
Dimensions of matrices being concatenated are not
Error in boutmodification1 (line 99)
totaldistancecovered =
Kindly help me with a solution to add the elements of that field. Thanks in advance.

Best Answer

The error message is clear: The contents of the fields output(:).distanceininches have different number of rows, such that they cannot be concatenated horizontally. Check this:
C = {output(:).distanceininches};
unique(cellfun('size', C, 1))
unique(cellfun('ndims', C)) % EDITED, typo removed
What do you get?
[EDITED] Either store the vectors as row vectors:
output(activityNum).distanceininches = zDistance(startind:endind).';
Or vertcat instead or horzcat (which is the same as [ and ]):
totaldistancecovered = sum(vertcat(output.distanceininches));