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.

Similar Reads

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....

Using sum(A, ‘all’)

...

Using sum(A, dim)

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....

Using sum(A, vecdim)

...

sum(___, outtype)

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....

Using sum(___, nanflag)

...