How to use sum(___, nanflag) In MATLAB
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
% MATLAB code for sum() with NaN values % Creating a vector of some numbers and NaN Values A = [1 -0.05 10.45 NaN 0.8 NaN 1.8 NaN]; % Calculating sum of the above vector % excluding NaN values 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
% MATLAB code for addition of % Using sum() function over sum() function. % Initializing an array A A = [1 2 3; 4 5 6] % Calling the sum() function % over the above array Sum = sum(sum(A)) |
Output:
A = 1 2 3 4 5 6 Sum = 21
Example 2:
Matlab
% MATLAB code for addition of % using sum() function over sum() function. % Initializing an array A A = [1 3 5; 2 4 6; 7 9 11; 8 10 12] % Calling the sum() function % over the above array Sum = sum(sum(A)) |
Output:
A = 1 3 5 2 4 6 7 9 11 8 10 12 Sum = 78
How to find sum of elements of an array in MATLAB?
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.