Calculating with vector containers

Hello everyone,

I was wondering how to do calculations with data stored in a vector. To be more accurate, there are two problems for which I could not find an answer:

Assuming I have a vector with an arbitrary number of values, how can I use it to make another vector the values of which are given by the following

BVector[0] = exp(-k*AVector [0])
BVector[1] = exp(-k*Avector [1])

and so on. In this, k is a constant factor, ideally of type double.

The other problem would be this: I want to substract two vectors from each other(value [0] from value [0], value [1] from value [1] and so forth), square the individual results and then sum them up. (so yes, I basically intend to calculate a root mean square deviation)

Thank you very much for your help.
Last edited on
Can you show us your code (and pretty please use [code][/code] tages)? What problems are you having (is it with the code itself or are you just unfamiliar with the vector container? If it's the latter check out this site's reference section: http://www.cplusplus.com/reference/vector/vector/)? It sounds like you are on the right track to answering your own questions:

1) Iterate over AVector, calculate what you need based on the current element and push_back into BVector,

2)
i) Ensure the two vectors are the same size
ii) Iterate over the range of 0 - size-1 [according to point i), size should equal the size of both vectors), find the difference, square that number then add it to a running sum (rough pseudo code):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vec_1, vec_2 #assume initialized
sum <- 0.0
diff <- 0.0

if (vec_1.size = vec_2.size)
{
 for (0 <= i < vec_1.size)
 {
  diff <- vec_1[i] - vec_2[i]
  diff <- diff * diff
  sum <- sum + diff
 }
}

else write 'the vectors have different sizes'


Not sure if that helped any or not...
1st.

Use loops:
1
2
for(int i = 0; i < AVector.size(); ++i)
    BVector[i] = exp(-k*AVector [i]);

Or use existing algorithms:
1
2
3
4
//Assuming vectors containing doubles
BVector.clear();
std::transform(AVector.begin(), AVector.end(), std::back_inserter(BVector), 
               [k](double x){ return exp(-k*x);} );


2nd

Looks like work for inner product.
http://en.cppreference.com/w/cpp/algorithm/inner_product
1
2
3
auto func = std::bind(std::pow, std::bind(std::minus<double>, _1, _2), 2);
double result = std::inner_product(AVector.begin(), AVector.end(), BVector.begin(), 0.0,
                   std::plus<double>(), func);
Or you can use similar loop with accumulator:
1
2
3
4
5
6
double acc = 0;
for(int i = 0; i < AVector.size(); ++i) {
    double d = BVector[i] - AVector [i];
    d*=d;
    acc += d;
}
Topic archived. No new replies allowed.