Prev Next

Convert Matrix to Scalar

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

Matlab or Octave
If x is an @(@ 1 \times 1 @)@ matrix,
     
x
behaves as if it were a scalar.

Example
     function [ok] = scalar_ok()
     ok  = true;
     m   = 2;
     n   = 3;
     u   = rand(m, n);
     x   = 5;
     % ----------
     v   = u * x;
     % ----------
     [m, n] = size(v);
     ok     = ok & (m == 2) & (n == 3); 
     for i = 1 : m
     	for j = 1 : n
     		ok = ok & abs(v(i,j) - u(i,j) * x(1,1)) < 1e-10;
     	end
     end
     return


C++
The following is a C++ implementation of conversion from a matrix to a scalar:
     
y = scalar(x)
where x is a @(@ 1 \times 1 @)@ ublas matrix<double> and y is a double.

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


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