sumSum of elements in an array
s = sum(A)A is a scalar, s is equal to A.A is a vector, s is the sum of all elements along the longer dimension of A.s is the sum of all elements of the corresponding vector of A along the first non-singleton dimension.A is empty, it returns an empty array.s = sum(A, k)s = sum(A), except that each element of s corresponds to a vector of A along its k-th dimension.k-th dimension has zero length, then it returns an empty array.💡 When adding up numbers by
sum, if any one of them isNaN, the result will beNaN.
a = [1 2 3; 1 2 3; 1 2 3];
% Creating a 3D array by repeating a matrix along the 3rd dimension.
b = repmat(a, [1, 1, 3])
% The sum along the 3rd dimension.
sum(b, 3)
b(:, :, 1) =
1.0000 2.0000 3.0000
1.0000 2.0000 3.0000
1.0000 2.0000 3.0000
b(:, :, 2) =
1.0000 2.0000 3.0000
1.0000 2.0000 3.0000
1.0000 2.0000 3.0000
b(:, :, 3) =
1.0000 2.0000 3.0000
1.0000 2.0000 3.0000
1.0000 2.0000 3.0000
ans =
3.0000 6.0000 9.0000
3.0000 6.0000 9.0000
3.0000 6.0000 9.0000