nnrales
nnrales

Reputation: 1519

Implement Matlab Syntax in C++

In Matlab the syntax to add elements to a matrix is

A = [12 62 93 -8 22; 16 2 87 43 91; -4 17 -72 95 6]
A =
    12    62    93    -8    22
    16     2    87    43    91
    -4    17   -72    95     6

I am building a small matrix library for educational purposes in C++ , the best way I have been able to come up with is to create an array and use list initialization , but it won't work for my purposes.

I need to be able to know how many rows are columns are there first so as to initialize the matrix.

Is there any way to copy this syntax in C++ . I would like the user to be able to create a matrix using a convenient method , rather than creating a matrix and going through each element , add a value .

I can handle the = using operator overloading , but what do I do about the right hand side. How do I deal with the [ ] or ; . I don't specifically need the colons or braces . Any other syntax will do too , as long as it is convenient for the user.

I realize it will be too much to ask you to implement it . All I want is some heuristic on how to do this , or a link with relevant information.

-Thank you

Upvotes: 3

Views: 168

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490278

I'm not sure I'd recommend it, but one obvious possibility would be:

std::vector<std::vector<int>> A = { 
    { 12 62 93 -8 22 },
    { 16 2 87 43 91  }, 
    { -4 17 -72 95 6 }
};

As long as it's purely educational, and you don't care a lot about wasting some space and the data not being contiguous, it should be fine.

Upvotes: 1

Paolo M
Paolo M

Reputation: 12767

In The C++ Programming Language (4th edition), Chapter 29, Stroutrup implements a Matrix class that satisfy your requirements. C++11 is required, though.

In particular, it can be initialized this way:

Matrix<int,2> m = {{1,2,3},{4,5,6}};

In particular, in §29.4.4, he define Matrix_init, a nested initializer_list, that is what you are looking for. Matrix_init<T,N> simply has Matrix_init<T,N-1> as its member type:

template<typename T, size_t N>
struct Matrix_init {
    using type = initializer_list<typename Matrix_init<T,N-1>::type>;
};

// specialization for N = 1
template<typename T>
struct Matrix_init<T,1> {
    using type = initializer_list<T>;
};

You can now write:

Matrix_init<int, 2>::type m{ {1,2}, {3,4} };

or, through a template alias,

template<typenameT,size_t N>
using Matrix_initializer = typename Matrix_init<T,N>::type;

Matrix_initializer<int,2> m{ {1,2}, {3,4} };

Upvotes: 2

Related Questions