Ask Your Question

# Sine or Cosine of every element in Mat (c++) I was wondering if there is any way to take the sine or cosine of every element in a matrix?

Thanks!

EDIT: For future reference, I did the Taylor expansion of Sine. For pretty good accuracy, I only had to calculate up to the fourth term. However, keep note that if you are trying to estimate sin(pi) or sin(-pi) you have to calculate additional terms (probably 8 total terms).

This link will be useful for those who want to do this: http://en.wikipedia.org/wiki/Taylor_s...

edit retag close merge delete

## Comments

Actually, you only need to go from -pi/4 to pi/4. For angles between pi/4 and pi/2, you can use the series for cos, substituting (pi/2-x) for your angle. Angles outside this range can be translated into it.

## 3 answers

Sort by » oldest newest most voted

How precise do you need it?

You can get within a few percent with a third order polynomial. You need to:

1) transfer all matrix values to the range -pi/2 to pi/2 by adding whole multiples of pi. (I assume matrix values are in radians, if they are in degrees multiply by pi/180).

2) calculate Sin(x)=x-(x^3)/6

3) for Cosine calculate Sin(pi/2-x)

if you want better precision you can use higher order polynomials: sin(x) is exactly the infinite polynomial x-(x^3/3!)+(x^5/5!)-(x^7/7!) +.... (look up "Taylor series" for more info) but the accuracy increases pretty fast as you add terms.

I have not tried it, but I guarantee that this would be faster than an element by element sin function (which is probably implemented by a polynomial approximation anyway).

guy

more

## Comments

1

Could you simply except the question instead of closing it down? We do not close quality solved questions :)

1

Excuse me . Can I know how to do the first step without any for loop (element by element)?

This should be the fastest way of retrieving Mat elements

Size contSize = mat.size();
if (mat.isContinous())
{
contSize.width *= contSize.height;
contSize.height = 1;
}
for (int i = 0; i < contSize.height; ++i)
{
T* ptr = mat.ptr<T>(y);
for (int j = 0; j < contSize.width; ++j)
{
ptr[j] = ...;
}
}


according to one of the core developers of OpenCV posted in this topic. Then inside the loop, do apply a sine or cosine on the value based on standard C++ functionality.

more

I haven't found such a function in the API, so I guess you need to loop over the Matrix yourself.

more

Official site

GitHub

Wiki

Documentation

## Stats

Asked: 2015-02-18 09:53:49 -0500

Seen: 5,164 times

Last updated: Feb 19 '15