Prev Next getstarted

Getting Started

Purpose
This is a quick introduction by example to the conversion of Matlab or Octave to C++ using ublas and this package.

Problem Definition
Suppose that we want to solve the following set of linear equations: @[@ \left( \begin{array}{cc} 1 & 2 \\ 3 & 4 \end{array} \right) \left( \begin{array}{cc} x_1 \\ x_2 \end{array} \right) = \left( \begin{array}{cc} 1 \\ 2 \end{array} \right) @]@

Matlab or Octave Solution

Program
a = [ 1., 2. ; 3., 4. ];
b = [ 1. ; 2. ];
x = a \ b


Output
Executing this program in Octave yields the following output:
 
x =

  0.00000
  0.50000

Conversion to C++ using C++

Program
# include <mat2cpp.hpp>
# include <boost/numeric/ublas/io.hpp>
int main(void)
{	using namespace mat2cpp;

	double a_data[] = {1., 2., 3., 4.};
	double b_data[] = {1., 2.};
	matrix<double> a(2, 2);
	matrix<double> b(2, 1);
	size_t i, j;
	for(i = 0; i < 2; i++)
	{	b(i, 0) = b_data[i];
		for(j = 0; j < 2; j++)
			a(i, j) = a_data[i * 2 + j];
	}	
	size_t rank;
	matrix<double> x = matrix_div(a, b, rank);
	std::cout << "x =" << x << std::endl;

	return 0;
}




Compile and Link
The following command compiles and links this program using the GNU C++ compiler:
g++ getstarted.cpp -o getstarted \
     -I
boost_dir -Lprefix_dir/lib -lmat2cpp -llapack
where boost_dir is the directory where the
     
boost_dir/boost/numeric/ublas/matrix.hpp
include file is installed (see the mat2cpp install instructions).

Output
 
x =[2,1]((0),(0.5))

Input File: omh/getstarted.omh