Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access array using matlab like indexing in C++?

Tags:

c++

I'm thinking about accessing C++ array using matlab like indexing, such as a[1 , :]. It would be very convenient.

I've overloaded operator [], but it seems not possible to have a[1, : ] syntax.

The solution I figured out is to write a script, which pre-processes the C++ source code and turns a[1, :] into a C++ function, such as col(a, 1). But this seems to be laborious.

Does anyone have a better solution? Thanks!!

like image 929
user2684645 Avatar asked Jan 12 '23 11:01

user2684645


2 Answers

The solution I figured out is to write a script, which pre-processes the C++ source code and turns a[1, :] into a C++ function, such as col(a, 1). But this seems to be laborious.

It is also brittle, error prone, compounding complexity, compounding any bugs and obscure. You're better off using macros (and you should never use macros like that).

Does anyone have a better solution?

Have you considered simply adding a function that does what you want? The syntax would not use array indexing, but it would be familiar to anyone looking at the code (including yourself two years from now) and explicit (as the function name would state what the function does).

like image 178
utnapistim Avatar answered Jan 29 '23 16:01

utnapistim


Boost multi array provides both 1-indexing and column views. range() replaces matlab operator:.

You can also define array views like 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)
like image 45
sbabbi Avatar answered Jan 29 '23 14:01

sbabbi