C ++ 2D growing array such as MATLAB

I read several posts about dynamically growing arrays in C, but I don’t see how to create a two-dimensional growing array (for example, in MATLAB).

I have a function to build an array for some image processing, but I don’t know what the size of this array (cols and rows) will be. How can I create this?

I read something about malloc and realloc. These features are portable or useful for this problem.

EDIT: SOLVED using the Armadillo library , a C ++ linear algebra library.

+4
source share
5 answers

Simplest with pointers

int nrows = 10; int ncols = 5; double* matrix = new double[mrows*ncols]; 

And then you can access it as if it is a 2D array like .

So, if you want matrix[row][col] , you would do

 int offset = row*ncols+col; double value = matrix[offset]; 

Also, if you need Matlab comfort as C ++ matrices, check out Armadillo

0
source

If you do image processing, you can use matrix and array types from opencv .

+1
source

By increasing an array like Matlab, I assume that you mean doing things like:

 mat = [mat; col] 

You can resize the matrix in C ++, but not with the syntax like above.

For example, you can use std::vector<std::vector<T>> to represent your matrix.

 std::vector<std::vector<int> > mat; 

Then, to add a column:

 for (int i=0; i<mat.size(); i++) mat[i].push_back(col[i]); 

or add line

 mat.push_back(row); // row is a std::vector<int> 
0
source

C ++ does not have a standard matrix class per se. I think that there were too many different applications of this class, which made one solution impossible for any size. There is an example and discussion in Straustrup’s book ( C ++ Programming Language (Third Edition)) regarding a relatively simple implementation for a numerical matrix.

However, it is much better to use an existing library for image processing.

You can take a look at CImg . I used it before and found it quick and well documented.

If you are on an AMD machine, I know that there is an optimized library for processing images from AMD, the Framewave Framewave Project .

Also, if you are using MATLAB style code, you can look at it ++ . I think the goal of the project is to make it as similar as possible to MATLAB.

0
source

+1 for OpenCV, especially useful if you are performing image analysis, as it abstracts the underlying data type (GRAYSCALE, RGB, etc.).

0
source

Source: https://habr.com/ru/post/1344321/


All Articles