This guide is going to discover how to sum array elements in MATLAB using the sum() function.
How to Sum Array Elements in MATLAB Using the sum() Function?
The sum() is a built-in function in MATLAB that is used for summing the elements of a vector or an array. This function accepts a vector or an array as an argument and returns the sum of all elements by adding them to each other.
Syntax
The sum() function has different syntaxes to be used in MATLAB, as given below:
S = sum(A,"all")
S = sum(A,dim)
S = sum(A,vecdim)
Here,
The function S = sum(A) computes the sum of array elements along its first dimension which should be greater than 1.
- If A is a vector, the S will be a scalar value that would be the sum of vector elements.
- If A is a matrix, the S will be a row vector having the sum of all column elements.
- If A is a multidirectional array, the S will be a multidirectional array containing the sum of array elements along the first dimension which should be greater than 1. In this case, the first dimension of S will become 1 while other dimensions will remain the same.
The function S = sum(A, ‘all’) calculates the sum of all elements of a vector, matrix, or multidirectional array and returns a single value.
The function S = sum(A, dim) calculates the sum of the elements of an array along the specified dimension dim.
The function S = sum(A, vectdim) computes the sum of the specified block or subarray of array A.
Examples
Follow the given examples for more understanding of summing up an array of elements in MATLAB using the sum() function.
Example 1: How to Find Sum of a Vector and Matrix in MATLAB?
In this example we compute the sum of a vector and a matrix element using the sum() function.
vect_sum = sum(x)
A = magic(4);
mat_sum = sum(A)
Example 2: How to Find the Sum of Arrays in MATLAB?
This MATLAB code first creates a three-dimensional array of random numbers using the rand() function. After that, it finds the sum of array elements using the sum(A), sum(A, ‘all’), sum(A, dim), and sum(A, vectdim) functions respectively.
S_1 = sum(A)
S_2 = sum(A, "all")
S_3 = sum(A, 3)
S_4 = sum(A, [2 1 3])
Conclusion
The sum() function is a useful MATLAB function that allows us to find the sum of the elements of a vector, a matrix, and a multidirectional array. This function uses different syntaxes to cater to various scenarios. This makes it a powerful function for data manipulation tasks. This tutorial has described different ways to find a sum of the elements of an array in MATLAB using the sum() function, allowing you to perform different computational tasks.