1. HowTo
  2. Matlab Howtos
  3. Sum Elements of a Matrix in MATLAB

Sum Elements of a Matrix in MATLAB

Created: May-07, 2021

  1. Sum the Elements of a Matrix Using a Loop in MATLAB
  2. Sum the Elements of a Matrix Using the sum() Function in MATLAB

This tutorial will discuss how to sum the elements of a matrix using a loop and sum() function in MATLAB.

Sum the Elements of a Matrix Using a Loop in MATLAB

In a matrix, there are two kinds of indexing; one is the row and column indexing in which we have to give the row and column number to access an element present in the matrix, second is the linear indexing in which we can access an element using only its linear index. For example, see the code below.

              clc m = [2 6 1; 17 19 18] row_col_index = m(2,3) linear_index = m(6)                          

Output:

              m =       2     6     1     17    19    18   row_col_index =      18   linear_index =      18                          

In the above code, we access the last element of the matrix using both kinds of indexing. In linear indexing, the elements are present in the matrix starting from the first column. So if you count from the first column, the last element is present at the sixth index. In order to iterate a matrix using row and column indexing, you require two loops, but in the case of linear indexing, you only require one loop. For example, let's iterate through a matrix using linear indexing and finding the sum of all the elements. See the code below.

              clc m = [2 6 1; 17 19 18]; total = 0; for i = 1:numel(m)     total = total + m(i); end sumOfElements = total                          

Output:

              sumOfElements =      63                          

In the above, we used the numel() function to get the total number of elements present in the given matrix and calculated the sum of all the elements present in the matrix using a loop and linear indexing.

Sum the Elements of a Matrix Using the sum() Function in MATLAB

To find the sum of all the elements of a matrix, you can use the sum() function. In the case of a matrix, you have to use the sum() function two times, one for rows and one for columns, but in the case of a vector, you have to use the sum() only one time. For example, let's find the sum of all the elements present in a given matrix. See the code below.

              clc m = [2 6 1; 17 19 18]; sumOfElements = sum(sum(m))                          

Output:

              sumOfElements =      63                          

You can also select the dimensions of the matrix on which you want to take the sum. Check this link for more details about the sum() function.

Contribute

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - MATLAB Matrix

  • MATLAB Transpose
  • The find() Function in MATLAB
  • Ezoic