• C++ Programming for Financial Engineering
    Highly recommended by thousands of MFE students. Covers essential C++ topics with applications to financial engineering. Learn more Join!
    Python for Finance with Intro to Data Science
    Gain practical understanding of Python to read, understand, and write professional Python code for your first day on the job. Learn more Join!
    An Intuition-Based Options Primer for FE
    Ideal for entry level positions interviews and graduate studies, specializing in options trading arbitrage and options valuation models. Learn more Join!

Generic class supporting arithmetic operators in C#

Joined
1/13/11
Messages
1,362
Points
93
I have the following class (which previously supported only an ordinary array type) converted to generic class. The code does the matrix multiplication but there is one problem. The line:

C++:
MM[i, j] += matrixA[i, k] * matrixB[k, j];

results in compile time error since generic type T cannot support +-*/ operators(since the class doesn't understand which value type the incoming parameter will be). So I have to define an interface named e.g. IOperatorSupport which will provide abstract prototypes of supporting those arithmetic operators. I'm gonna take a long road thinking and implementing such interface. Has anyone got such interface already defined? Or I'm gonna do it myself this night... Thanks

Here's the class itself:

C++:
public class Lin_Alg<T>where T: struct,  IOperatorSupport //note this interface
    {
        public static List<T>[,] MMult<T>(List<T>[,] matrixA, List<T>[,] matrixB)
        {
            int n = matrixA.GetLength(0);
            int m = matrixA.GetLength(1);
            int a = matrixB.GetLength(0);
            int b = matrixB.GetLength(1);
            List<T>[,] MM = new List<T>[n, b];

            int k = 0;

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < b; j++)
                {
                    while (k < m)
                    {
                        MM[i, j] += matrixA[i, k] * matrixB[k, j];    //offending line
                        k++;
                    }
                    k = 0;
                }
            }
            return MM;
        }
    }
 
Instead of re-inventing the wheel (unless you have some specific classes you need to treat as matrices), why do you not have a look at Math.NET. They have matrix implementations (I do not know however if it does what you want).

Niels
 
Instead of re-inventing the wheel (unless you have some specific classes you need to treat as matrices), why do you not have a look at Math.NET. They have matrix implementations (I do not know however if it does what you want).

Niels

I'm not reinventing the wheel at all. The reason why I cannot treat it as an ordinary matrix like double[,] matrixA is that I need type safety and it also hurts the runtime execution speed. double[,] (ordinary matrix as you suggest) is an array type which expects to receive an object parameter. However, while giving double, int, float or any value type CLR performs the following 4 memory operations:

1) Creates and allocates an object on heap.
2) Internally boxes and transfers the value type from the stack to that object on the heap.
3) While retrieving it internally unboxes again and passes the value back from the heap to the stack.
4) Finally unused object on the heap is garbage collected.

So generics provide me the way to avoid all the above issues. So I need more type safe class receiving value types. I also used generics in order to avoid overloading the method many times for each value types to be passed:int,double,float,single,etc.

Thanks for your answer
 
BTW, which Math.NET library are you talking about? System.Math?
 
Thanks a lot Niels, but I'm just using it for educational purpose so I need to define it myself. I have several such libraries which are highly optimized.
 
You can us the Reflection API to generate the code for operators acting on generic types.

I would not be a fan of using interfaces, it is OO and the current issue is generics.
 
You can us the Reflection API to generate the code for operators acting on generic types.

I would not be a fan of using interfaces, it is OO and the current issue is generics.

Thanks a lot! I managed it already. Overloaded the operators. Now I'm able to multiply matrices with simpler syntax than invoking methods explicitly.
 
One generics' feature that is missing in C# is the ability to support integral types as parameter:

array<class T, int N>

array<double, 100> myFixedArray;

I suppose we can't have everything :)
 
One generics' feature that is missing in C# is the ability to support integral types as parameter:

array<class T, int N>

array<double, 100> myFixedArray;

I suppose we can't have everything :)

double is a reference type? Isn't T a struct?
 
Did you ever think of writing an API to integrate R with C++. IT will be useful when your matrix grows in size and the loops start to kill you.

my 2 cents
 
In C#, double is a value type; T, don't know.
The beauty of C++ - in contrast to C# - is that the developer has complete control over the language.
Yes I thought you declared T as class and passed double as an argument.
 
Did you ever think of writing an API to integrate R with C++. IT will be useful when your matrix grows in size and the loops start to kill you.

my 2 cents

That API already exists for both ends. You can call C++ functions from R via RCPP or RCOM (for C++, C#). You can also integrate the R engine into C++, C#... via the statconnector.
 
Has anyone tried to split 2 matrices into 2 parts each (or more) and executing the matrix multiplication algorithm on separate threads? I want to define a matrix as a type - class or structure and have not decided yet which to choose. The advantage of class would be that I'd be able to derive from that matrix some other kind of matrices gaining the polymorphic interface defined in the abstract (possibly but not necessarily) base class. But the disadvantage is that for some reasons I don't want to allocate it's object on the heap. Advantage of structure is of course it will be allocated on the stack, but I won't be able to subclass from it. Any ideas?
 
Has anyone tried to split 2 matrices into 2 parts each (or more) and executing the matrix multiplication algorithm on separate threads?

Yes - this is how people are doing matrix multiplication for the last 40 years, or so.
 
Yes - this is how people are doing matrix multiplication for the last 40 years, or so.

I know it is common...actually what I'm trying to grasp however is the CPU properties. How is it depended on what processor I have in terms of thread number? Put another way - how many threads (max) can I execute paralelly given some particular CPU?... not the speed of executing the algorithm...
 
Put another way - how many threads (max) can I execute paralelly given some particular CPU?... not the speed of execution the algorithm...

You could run as many threads as your operating system allow, however too many of them are just going to thrash. So one would usually check, in the specific processor documentation, how many threads could be executing simultaneously, and then profile the code around that number to come up with best value. But this is probably the least important issue for an efficient multi-threaded matrix multiplication (and the number of threads is usually just left as an additional argument for the multiplication procedure anyway) - much more important is the structuring of the algorithm itself, so that cache hierarchy is properly used and that multiplication code in individual threads is vectorized.
 
the number of threads is usually just left as an additional argument for the multiplication procedure anyway

That's how I've done it. I'll finish matrices soon.
 
Back
Top