Re: vectorized computation in C++ such as those in Matlab (Matlab to C++)?
- From: Rune Allnor <allnor@xxxxxxxxxxxx>
- Date: Tue, 22 Jul 2008 08:54:14 -0700 (PDT)
On 22 Jul, 16:08, Luna Moon <lunamoonm...@xxxxxxxxx> wrote:
Dear all,
Can C++/STL/Boost do the vectorized calculation as those in Matlab?
No. The computations are done element-wise, but you can write wrapper
functions which let you as user view things as vector operations.
For example, in the following code, what I really want to do is to....
send in a vector of u's.
If vectorized computation is not facilitated, then I have to call this
function millions of times.
But if vectorized computation is okay, then I can send in just a u
vector with batch elements a time.
I assume you have a few million elements you want to send as argument
to the computations, and that each operation on a scalar will produce
a scalar result. So the vector is only a container for the input and
output data. Here is an example on how to do things (not a complete
program):
#include <vector> // You need this one to use the
vector class
#include <math> // You need this to get access to
some
// maths functions
std::vector<double> input; // Declare a vector for the input
double myfunction(double x)
{
// Implement your computations here, e.g.
y=sin(x);
}
std::vector<double> myfunction(std::vector<double> x)
{
// Wrapper function that lets you call the function
// for each element in a vector
std::vector<double> y; // Declare the vector for results
y.reserve(x.size()); // You already know how many elements y
// needs to hold, so reserve the space
// up front
for (int n=0;n<x.size();++n) // Now the loop.
{
y[n]=myfunction(x[n]); // Note the same name on the
functions!
}
return y;
}
and there you are. When you want to use this you just write
std::vector<double> x;
// Initialize x
std::vector<double> y = myfunction(x);
as you would in matlab. You just tell the compiler what you want and
the compiler is assigned the task of picking exactly which variant
of 'myfunction' is used, based on the type of the argument you
call it with.
Try this:
std::vector<double> x;
// Initialize x
std::vector<double> y = myfunction(x);
double a = 3.14;
double b;
b = myfunction(a);
Two functions with the same name are used, but since the argument
types are different, the compiler figures out which variant to
use in each case.
Rune
.
- Follow-Ups:
- Prev by Date: Re: textscan and large documents
- Next by Date: Re: Weighted random number generator
- Previous by thread: textscan and large documents
- Next by thread: Re: vectorized computation in C++ such as those in Matlab (Matlab to C++)?
- Index(es):
Relevant Pages
|