MATLAB Language Sum, mean, prod & co


Given a random vector

v = rand(10,1);

if you want the sum of its elements, do NOT use a loop

s = 0;
for ii = 1:10
    s = s + v(ii);

but use the vectorized capability of the sum() function

s = sum(v);

Functions like sum(), mean(), prod() and others, have the ability to operate directly along rows, columns or other dimensions.

For instance, given a random matrix

A = rand(10,10);

the average for each column is

m = mean(A,1);

the average for each row is

m = mean(A,2)

All the functions above work only on one dimension, but what if you want to sum the whole matrix? You could use:

s = sum(sum(A))

But what if have an ND-array? applying sum on sum on sum... don't seem like the best option, instead use the : operator to vectorize your array:

s = sum(A(:))

and this will result in one number which is the sum of all your array, doesn't matter how many dimensions it have.