Is it possible to access an array using matlab, such as indexing in C ++?

I am thinking of accessing a C ++ array using matlab type indexing, for example a[1 , :] ,: a[1 , :] . That would be very convenient.

I overloaded the [] operator, but the syntax a[1, : ] seems impossible.

The solution I understood is to write a script that preprocesses the C ++ source code and turns a[1, :] into a C ++ function, for example col(a, 1) . But it seems laborious.

Does anyone have a better solution? Thanks!!

+4
source share
2 answers

The solution I found out was to write a script that pre-processes the C ++ source code and turns [1 ,:] into a C ++ function, such as col (a, 1). But it seems laborious.

It is also fragile, error prone, complexity of difficulties, aggravates any errors and unclear. You are better off using macros (and you should never use such macros).

Does anyone have a better solution?

Have you considered simply adding a function that does what you want? The syntax will not use array indexing, but it will be familiar to anyone looking at the code (including you in two years) and explicit (since the name of the function will indicate what the function is doing).

+6
source

The Boost multi-user array provides both single-index and column views. range() replaces the matlab : operator.

You can also define array representations, as in this example, from the documentation

 myarray[ boost::indices[range()][range() < 5 ][4 <= range().stride(2) <= 7] ] 

Which is equivalent to matlab

 myarray(:,1:4,4:2:7) 
+3
source

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


All Articles