This is a very quick question. I am using newmat so matrices can be used as if they are simple variables from my understanding. I am writing a recursive code and need to do something like the following:
double f(double x) {
return x*x - 4;
}
int main() {
int y = 2 * f(5); //y = 2 * (5*5 - 4)
//Your not multiplying by a function, but by whatever value it returns.
}
So I thought I had figured this one out but I can only get singular solutions that don't apply to all inputs.... shoooooot. Here is my actual code for the matrix * recursive function part that I am trying to figure out:
1 2 3 4
if(k > 1 && k % 2!= 0){
cout << 2 << endl;
C=(B*B);
B * repeated_squaring(B*B, n, (k-1)/2);
A bit of an explanation. I am trying to write a recursive code for the Repeated Squaring Algorithm, but with a matrix instead of an integer. B is my matrix, n is an input specifying the matrix size and does not change, this is only for a square matrix so multiplication is always possible, and k is the power that the matrix is being multiplied to. This is the part of the function that should be initiated when k is odd.
ALSO: C is in there because I was trying to manipulate the recursive solution to not have to be multiplied by B by changing the multiplication inside the matrix. Unfortunately this can't be done so that it works for any n or k.
Please help if you happen to still be awake! I do appreciate anything and everything and any suggestion is worth a shot, i'm frankly out of ideas at this point.
//Assume to following matrix class is used:
class Matrix
{
private:
//internal stuff
...
public:
constint rows;
constint cols;
/**
* @return The identity matrix of size n by n
* @throws InvalidArgumentException if n == 0
*/
static Matrix identity(unsignedint n);
/**
* @return The inverse matrix
* @throws NonSquareMatrixException
* @throws SingularMatrixException
*/
Matrix inverse();
/**
* @param a
* @param b
* @return a times b, using standard matrix multiplication
* @throws InvalidArgumentException if a.cols != b.rows
*/
friend Matrix operaotr*(const Matrix &a, const Matrix &b);
/**
* (exponentiation)
* @param n, the exponent
* @return the given matrix to the power of n if n is positive,
* the identity matrix if n is negative,
* or the inverse of the given matrix to the -n power if n is negative
* @throws NonSquareMatrixException
* @throws SingularMatrixException if n is less then 0 and the given matrix is singular
*/
Matrix pow(int n);
};
//definitions for Matrix class's members and friends
...
Matrix Matrix::pow(int n) {
if( rows != cols )
throw NonSquareMatrixException();
if( n == 1 )
return Matrix::identity(rows);
if( n < 0 )
return pow(-n).inverse();
//to avoid infinite recursion
if( n == 2 )
return (*this) * (*this);
//n is odd
if( n % 2 != 0 )
return *this * pow((n - 1) / 2).pow(2);
//n is even
return pow(n / 2).pow(2);
}