How to find sum of elements of an array in MATLAB?
Last Updated :
29 Jul, 2021
This article will discuss the “Finding sum of elements of an array” in MATLAB that can be done using multiple approaches which are illustrated below.
Using sum(A)
This is used to return the sum of the elements of the array along the first array dimension whose size does not equal 1. It returns a row vector containing the sum of each column.
Example:
Matlab
A = [1 2 3; 4 5 6]
Sum = sum(A)
|
Output:
A =
1 2 3
4 5 6
Sum =
5 7 9
Using sum(A, ‘all’)
sum(A, ‘all’) is used to calculate the sum of all elements of A. And this syntax is valid only for MATLAB versions R2018b and later.
Example:
Matlab
A = [1 3 5; 2 4 6; 7 9 11; 8 10 12]
Sum = sum(A)
|
Output:
A =
1 3 5
2 4 6
7 9 11
8 10 12
Sum =
18 26 34
Using sum(A, dim)
sum(A, dim) is used to return the sum along dimension dim. For example, sum(A, 2) is a column vector containing the sum of each row.
Example:
Matlab
A = [1 3 5; 2 4 6; 7 9 11; 8 10 12]
Sum = sum(A, 2)
|
Output:
A =
1 3 5
2 4 6
7 9 11
8 10 12
Sum =
9
12
27
30
Using sum(A, vecdim)
This function is used to sum the elements of A based on the dimensions specified in the vector vecdim.
Example:
Matlab
A = [1 3 5; 2 4 6; 7 9 11; 8 10 12; 13 14 15]
Sum = sum(A, [2, 3])
|
Output:
A =
1 3 5
2 4 6
7 9 11
8 10 12
13 14 15
Sum =
9
12
27
30
42
sum(___, outtype)
sum(___, outtype) is used to return the sum with a specified data type, using any of the input arguments in the previous syntaxes. Here the outtype can be ‘default’, ‘double’, or ‘native’.
Example:
Matlab
A = int32(1:5);
Sum = sum(A, 'native' )
|
Output:
Sum = 15
Using sum(___, nanflag)
sum(___, nanflag) is used to specify whether to include or omit NaN values from the calculation for any of the previous syntaxes. sum(A,’includenan’) includes all NaN values in the calculation while sum(A,’omitnan’) ignores them.
Example:
Matlab
A = [1 -0.05 10.45 NaN 0.8 NaN 1.8 NaN];
Sum = sum(A, 'omitnan' )
|
Output:
Sum = 14
Lets see addition of Using sum() function over sum() function. It will return Sum of the array’s elements entirely.
Example 1:
Matlab
A = [1 2 3; 4 5 6]
Sum = sum(sum(A))
|
Output:
A =
1 2 3
4 5 6
Sum = 21
Example 2:
Matlab
A = [1 3 5; 2 4 6; 7 9 11; 8 10 12]
Sum = sum(sum(A))
|
Output:
A =
1 3 5
2 4 6
7 9 11
8 10 12
Sum = 78
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...