# Best way to apply a function to each element of Mat.

Hi,

I need to apply a function to each element of a matrix (in a Mat object). For example, I need to calculate the hyperbolic tangent (tanh) of each value in the Mat.

I know that I can access each element of a Mat M by `M.at<T>(i,j)`

as such I can implement the algorithm (just pseudocode) as follows:

```
for( i = ... )//through each row in Mat M
for(j = ...)//through each column
M.at<T>(i,j) = tanh( M.at<T>(i,j) );
```

This works. But it is rather slow as I'm working on a real time system that needs to do the same operation over and over.

Is there is perhaps someway to collectively apply the same function (perhaps by passing a function pointer) to each element in a Mat at the same time? That would be quite helpful.

Thanks in advance :)

For a quick solution, see http://answers.opencv.org/question/830/hyperbolic-tangent-on-image/ . I agree that providing a template-based opencv foreach function is a good long-term solution.

Agree too, but other langauge do not support template, if openCV do provide a template-based foreach function, this has a high change to become a c++ only api