Prev Next

Sum The Elements of a Matlab

Syntax
Matlab or Octave y = sum( sum(x) )
C++ y = sum(x)

Matlab or Octave
If x is an @(@ m \times n @)@ matrix,
     
y = sum( sum(x) )
sets y to the sum of the elements in the matrix x. If either m or n is equal to one,
     
y = sum(x)
also sets y to the sum of the elements in the matrix x.

Example
     function [ok] = sum_ok()
     ok  = true;
     m   = 2;
     n   = 3;
     x   = rand(m, n);
     % ------------------
     y   = sum( sum(x) );
     % ------------------
     [p, q] = size(y);
     ok     = ok & (p == 1) & (q == 1); 
     ok     = ok & abs( y - ones(1, m) * x * ones(n, 1) ) < 1e-10;
     return


C++
The following is a C++ implementation of the Matlab or Octave syntax above:
     
y = sum(x)
where x is an @(@ m \times n @)@ ublas matrix<double> and y is a double.

Example
     # include <mat2cpp.hpp>
     bool sum_ok(void)
     {	bool   ok  = true;
     	using namespace mat2cpp;
     
     	size_t i, j, m(2), n(3);
     	matrix<double> x = rand(m, n);
     	// ---------------
     	double y = sum(x);
     	// ---------------
     	double check = 0.;
     	for(i = 0; i < m; i++)
     	{	for(j = 0; j < n; j++)
     			check += x(i,j);
     	}
     	ok &= std::fabs(check - y) < 1e-10;
     	return ok;
     }


Source
The file sum.cpp contains the C++ source code for this operation.
Input File: omh/sum.omh