Home > Mobile >  Adding corresponding elements of vectors C
Adding corresponding elements of vectors C

Time:11-15

I have been doing a bit of brushing up on my Linear Algebra basics and figured a fun way to do so would be with code. I am trying to create a function that performs Vector addition given two vectors of different lengths. For example if we have two vectors v1 = 0, 7, 3 and v2 = 1, 2, 4 our sum would be 1, 9, 7. My end goal is to be able to create a function that accepts n number of vectors of any numeric type and perform traditional vector addition on them.

So far I am able to naively do so by just traversing the first vector and adding each element to the corresponding element of second vector.

int main() {
    // create vectors 
    std::vector<int> v1 = {0, 7, 3, 4}; 
    std::vector<int> v2 = {1, 2, 4, 1, 6}; 
    
    int i = 0;
    // iterate over v1 adding to the corresponding element in v2
    for (i; i < v1.size(); i  ) {
        int sum = v1[i]   v2[i];
        printf("sum - %d\n", sum);
    }
    return 0;
}

What would the logic look like to add the elements of two vectors of different sizes?

CodePudding user response:

vector<int> sum;
for (int i=0; i < std::min(v1.size(),v2.size()); i  ) {
    sum.push_back(v1[i]   v2[i]);
}

or

vector<int> sum;
for (int i=0; i < std::max(v1.size(),v2.size()); i  ) {
    int a=0;
    if(i<v1.size()) a  = v1[i];
    if(i<v2.size()) a  = v2[i];
    sum.push_back(a);
}

CodePudding user response:

The requirements of your question are summarized as

  1. an function that accepts different types to sum up on vectors;
  2. the sum function may encounter different lengths of vectors;

1. Use template to define generic functions

Suppose you take the first arg lhs to store the result.

template<typename LHS, typename RHS>
void vsum(LHS& lhs, RHS const& rhs) {
    assert(lhs.size() == rhs.size());
    auto lhs_iter = lhs.begin();
    auto rhs_iter = rhs.cbegin();
    while(lhs_iter != lhs.end() && rhs_iter != rhs.cend()) {
        *lhs_iter  = *rhs_iter;
          lhs_iter; 
          rhs_iter;
    }
}

std::vector<double> lhs{1.2, 3.4, 5.6};
std::vector<int>    rhs{7, 8, 9};

vsum(lhs, rhs);

Then variable lhs now hold the sum vector result.

Note that I use assert here to check length in debug phase, which mean the inputs are guaranteed to be valid length in vsum function. Comment this assert sentence, you will get a minimum length version.

2. Careful check and prepare inputs

To Answer 2, it is alway not the result as you expected when accepting the default minimum length of your input vectors. It is a good practice to throw, or at least print a warning message in logger or to std::cerr when inputs does not met your constrain that "vectors on different dimension cannot be added" in linear algebra.

To keep input clean and tidy, provide a project function to map vector of higher dim to given dim. It is simple and straightforward.

template<std::size_t DIM, typename T>
void project(std::vector<T>& vec) {
    vec.resize(DIM, T(0));
}

constexpr int k_physical_dim = 3;
std::vector<double> data_vec{3.4, 5.6};
project<k_physical_dim>(data_vec);

By this, you trim data_vec to specific dimension you are working on.

3. Get familiar with <algorithm.h> header

When get familiar with template and C type operations, it is strongly advised to use algorithm lib instead. You can read reference here.

Hope this may help you.

  • Related