I am wondering whether there is a C++ function written by someone can do the following matrix operation.
Thanks,
L
-------------
MATLAB supports a type of array indexing that uses one array as the index into another array. You can base this type of indexing on either the values or the positions of elements in the indexing array.
Here is an example of value-based indexing where array B indexes into elements 1, 3, 6, 7, and 10 of array A. In this case, the numeric values of array B designate the intended elements of A:
A = 5:5:50
A =
5 10 15 20 25 30 35 40 45 50
B = [1 3 6 7 10];
No rudeness taken. I was intrigued with this question and wasted my lunch hour slapping something together. My solution is more complex that the way you wrote it.
My main goal was trying to mimic the matlab notation A(B);. That's why I made it a class. Then I started adding error checking and utilities, and things got more cluttered. I could have stripped it down to a sleeker version, but I was in my error-catching mode.
@OP,
Yes, my code compiles and works. I have no idea what symbol your compiler does not see. Your error message is almost meaningless.
#include <iostream>
#include <valarray>
#include <iomanip>
int main()
{
std::valarray<int> a = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 } ;
std::valarray<std::size_t> b = { 1, 3, 6, 7, 10 } ;
b -= 1 ; // index of the first element in C++ sequences is zero, not one
const std::valarray<int> c = a[b] ; // construct from indirect_array
for( int v : c ) std::cout << v << ' ' ;
std::cout << '\n' ;
for( int v : a ) std::cout << std::setw(6) << v ;
std::cout << '\n' ;
const std::valarray<int> d = a * 99 ;
a[b] += d[b] ; // modify a via indirect array
for( int v : a ) std::cout << std::setw(6) << v ;
std::cout << '\n' ;
a[ a%100 == 0 ] = -9 ; // assign -9 to elements that are divisible by 100 (via mask array)
for( int v : a ) std::cout << std::setw(6) << v ;
std::cout << '\n' ;
}