how can i find the sum of matrix elements

5 views (last 30 days)
Luzan Obeidat
Luzan Obeidat on 16 Apr 2014
Edited: Star Strider on 16 Apr 2014
if i have a two dimension matrix i want to create a for loop to compute the summation of element in this matrix like : sum= 0 for i=1 to n for j= 1 to m sum= sum + a[j,j] but in matlab!!!

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 16 Apr 2014
You can use sum function
sum(A(:))

Star Strider
Star Strider on 16 Apr 2014
Edited: Star Strider on 16 Apr 2014
If you want to sum the diagonal elements of a, I suggest:
a = rand(5,5);
sd = sum(diag(a));
Do not use sum as a variable name. It is a built-in MATLAB function, and using it as a variable name will cause problems later in your code.
If you want the sum of all the elements in your matrix, I suggest:
sa = sum(a(:));

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!