Prev Next

Matlab or Octave Elementwise Unary Functions

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

Matlab or Octave
If x is an @(@ m \times n @)@ matrix,
     
y = f(x)
sets y to the @(@ m \times n @)@ matrix with @[@ y_{i,j} = f( x_{i,j} ) @]@ where f can be any of the following functions:
f Description
abs absolute value
log logarithm

Example
     function [ok] = element_unary_ok()
     ok  = true;
     m   = 2;
     n   = 3;
     x   = rand(m, n);
     % ---------------
     abs_x   = abs(x);
     log_x   = log(x);
     % ---------------
     for i = 1 : m
     	for j = 1 : n
     		ok = ok & ( abs_x(i, j) == abs(x(i, j)) );
     		ok = ok & ( log_x(i, j) == log(x(i, j)) );
     	end
     end
     return


C++
The following is a C++ implementation of the elementwise unary functions above with the syntax:
     
y = f(x)
where x and y ublas matrix<double> objects with size @(@ m \times n @)@.

Example
     # include <mat2cpp.hpp>
     # include <limits>
     
     bool element_unary_ok(void)
     {	bool   ok  = true;
     	using namespace mat2cpp;
     	double eps = 10. * std::numeric_limits<double>::epsilon();
     
     	size_t i, j, m(2), n(3);
     	matrix<double> x = rand(m, n);
     	// ---------------------------
     	matrix<double> abs_x = abs(x);
     	matrix<double> log_x = log(x);
     	// ---------------------------
     	for(j = 0; j < n; j++)
     	{	for(i = 0; i < m; i++)
     		{	ok &= std::fabs( abs_x(i, j) - std::fabs(x(i, j)) ) < eps;
     			ok &= std::fabs( log_x(i, j) - std::log(x(i, j))  ) < eps;
     		}
     	}
     	return ok;
     }


Source
The file element_unary.cpp contains the C++ source code for these functions.
Input File: omh/element_unary.omh