I’m trying to create a matrix data structure in C. I have a struct and have a two dimensional void pointer array (size is dynamically defined at the heap) for the cargo part(data) in this struct.
Given a column index, I want to get the values of this column in a one dimensional array. It is easy to this with one for or while loop. But if the number of rows in this matrix is N, then it’ll take O(N) time for getting a column vector. Can I do this more efficiently with memory operations like memcpy and how? Otherwise how can I improve the performance(My data is pretty structured and I need to store this in some kind of matrix).
If you want to copy the data in your matrix, you can’t do it in less than O(N) time whether it is a row or a column, except for small N where hardware features might help.
However, if your matrices are immutable, you can use smoke and mirrors to give the illusion of having a separate column vector.
The below code is typed straight in to the answer text box and has not even been compiled. Use at your own risk!
Your matrix type is defined as a struct thus:
To create a brand new matrix (I’ve left out all the error handling to make it simpler).
To access an element (again no error handling, eg bounds errors)
To create a new matrix from a rectangular region of another matrix (again, error handling needed)
To create a new matrix from a column in another matrix:
To free a matrix
If you want mutable matrices, any time you modify an element, check the refCount and if it is greater than 1, copy the DataRef before modifying it (decrement the refCount on the old dataRef), otherwise modify the dataRef in place.
Now the above uses lots of mallocs and so might be less efficient than the naive implementation for small matrices. However, you could maintain a list of unused DataRef structs and Matrix structs and instead of freeing them when you are done, put them on the free list. When allocating new ones, get the structs from the free lists unless they are empty. That way, getting a matrix that represents a column of an existing matrix will often take constant time.