I'm looking for a clean way to shed non-contiguous indices in using the Armadillo linear algebra library for C++. I have some code included below, but it seems like there is probably a better way to do it. Any advice appreciated.
The following code works for removing indexes in ind from (column) vector a, but feels clunky.
for(uword k = ind.n_elem; k>0; k--){
a.shed_row(ind(k-1));
}
Any thoughts?
Here is one way using a templated function for dropping rows based on a (sorted) uvec of indexes to exclude. You get the missing indexes from std::set_difference and then go from there.
#define ARMA_USE_CXX11
#include <armadillo>
#include <iostream>
template <class T>
T drop_rows(T a, arma::uvec exclude) {
arma::uvec full_range = arma::regspace<arma::uvec>(0, a.n_rows - 1);
std::vector<int> diff;
std::set_difference(full_range.begin(), full_range.end(),
exclude.begin(), exclude.end(),
std::inserter(diff, diff.begin()));
T b = a.rows(arma::conv_to<arma::uvec>::from(diff));
return b;
}
int main() {
arma::uvec exclude = {0, 1, 4};
arma::vec a = arma::linspace<arma::vec>(100, 500, 5);
arma::vec b = drop_rows(a, exclude);
std::cout << b << std::endl;
arma::mat A = arma::mat(5, 5, arma::fill::eye);
arma::mat B = drop_rows(A, exclude);
std::cout << B << std::endl;
return 0;
}
Related
I have a 2d boost matrix (boost::numeric::ublas::matrix) of shape (n,m), with the first column being the timestamp. However, the data I'm getting is out of order. How can I sort it with respect to the first column, and what would be the most efficient way to do so? Speed is critical in this particular application.
As I commented ublas::matrix might not be the most natural choice for a task like this. Trying the naive approach using matrix_row and some range magic:
Live on Coliru
#define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/irange.hpp>
#include <boost/range/algorithm.hpp>
#include <iomanip>
#include <iostream>
using namespace boost::adaptors;
using Matrix = boost::numeric::ublas::matrix<float>;
using Row = boost::numeric::ublas::matrix_row<Matrix>;
static auto by_col0 = [](Row const& a, Row const& b) { return a(0) < b(0); };
int main()
{
constexpr int nrows = 3, ncols = 4;
Matrix m(nrows, ncols);
for (unsigned i = 0; i < m.size1(); ++i)
for (unsigned j = 0; j < m.size2(); ++j)
m(i, j) = (10 - 3.f * i) + j;
std::cout << "before: " << m << "\n";
auto getrow = [&](int i) { return Row(m, i); };
sort(boost::irange(nrows) | transformed(getrow), by_col0);
std::cout << "after: " << m << "\n";
}
Does sadly confirm that the abstraction of the proxy doesn't hold:
before: [3,4]((10,11,12,13),(7,8,9,10),(4,5,6,7))
after: [3,4]((10,11,12,13),(10,11,12,13),(10,11,12,13))|
Oops.
Analysis?
I can't say I know what's wrong. std::sort is defined in terms of ValueSwappable which at first glance seems to work fine for matrix_row:
auto r0 = Row(m, 0);
auto r1 = Row(m, 1);
using std::swap;
swap(r0, r1);
Prints Live On Coliru
Maybe this starting point gives you something helpful. Since it's tricky like this, I'd highly consider using another data structure that is more conducive to your task (boost::multi_array[_ref] comes to mind).
I have 2 vectors of ints.
say the first one has (2,1).
and the second one (1,1).
I am trying to subtract numbers like this:
2 - 1,
1 - 1
then I need to add these 2 numbers so the final answer would be 1.
I've tried a for loop, but it's subtracting each number from each element, instead of only the first one.
This is what I've tried so far.
vector<int> temp;
for(unsigned i =0; i < Vec1.size(); i++)
for(unsigned o =0; o < Vec2.size(); o++)
temp.push_back(Vec1.at(i).nums- Vec2.at(o).nums);
//where nums, are just the numbers showed above
The output as you would expect is :
1
1
0
0
and I need it to be:
1
0
then I can just do a for loop to add all the ints together.
Any help, would be greatly appreciated!
I've tried a for loop, but it's subtracting each number from each element, instead of only the first one.
You are not doing it the right way. You have been using cascaded for loops and hence, you are subtracting each element of first vector from each element of second vector.
There are two ways to correctly implement:
One involves writing your own functions to subtract two vector and then adding elements of the result.
#include <iostream>
#include <vector>
std::vector<int> subtract(const std::vector<int>& a, const std::vector<int>& b)
{
std::vector<int> result;
const int SIZE = std::min(a.size(), b.size());
for (int i = 0; i < SIZE; i++)
result.push_back(a[i] - b[i]);
return result;
}
int addAllElements(const std::vector<int>& a)
{
int result = 0;
for (auto i: a)
result += i;
return result;
}
int main(void)
{
std::vector<int> a = {2, 1};
std::vector<int> b = {1, 1};
std::cout << "Result is " << addAllElements(subtract(a, b)) << std::endl;
return 0;
}
The other method (preferred) involves using STL:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
int main(void)
{
std::vector<int> a = { 2, 1 };
std::vector<int> b = { 1, 1 };
std::vector<int> result;
std::transform(std::begin(a), std::end(a), std::begin(b), std::back_inserter(result), [](const auto a, const auto b)
{
return a - b;
}
);
int sumAllElements = std::accumulate(result.begin(), result.end(), 0);
std::cout << "Result is " << sumAllElements << std::endl;
return 0;
}
The above code uses lambda expression. To know more about them, see this link.
std::accumulate sums all the elements of the container and std::transform performs the transformation (specified in it's fifth argument) on two vectors and put the result in a different vector. We have used lambda expression to perform the required sub operation.
EDIT:
To implement it without lambda is also easy. You can use function pointers.
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
double subtract(const double a, const double b)
{
return a - b;
}
int main(void)
{
std::vector<int> a = { 2, 1 };
std::vector<int> b = { 1, 1 };
std::vector<int> result;
std::transform(std::begin(a), std::end(a), std::begin(b), std::back_inserter(result), subtract);
int sumAllElements = std::accumulate(result.begin(), result.end(), 0);
std::cout << "Result is " << sumAllElements << std::endl;
return 0;
}
There are various advantages of using lambda expression.
NOTE:
You can also use std::minus instead of defining you own function. Like this:
std::transform(std::begin(a), std::end(a), std::begin(b), std::back_inserter(result), std::minus<int>());
In C++17, you can combine std::transform and std::reduce/std::accumulate calls with std::transform_reduce:
const std::vector<int> vec1 {2, 1};
const std::vector<int> vec2 {1, 1};
auto res = std::transform_reduce(vec1.begin(), vec1.end(),
vec2.begin(),
0,
std::plus<>(),
std::minus<>());
Demo
Here is an example using the STL:
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> vec1 {2, 1};
std::vector<int> vec2 {1, 1};
std::vector<int> temp;
std::transform(begin(vec1), std::end(vec1), std::begin(vec2),
std::back_inserter(temp), [](const auto a, const auto b) {return a - b;});
auto sum = std::accumulate(temp.begin(), temp.end(), 0);
std::cout << "Result: " << sum << "\n";
return 0;
}
Write a function which will take two arrays as parameters and add the individual
elements of each array together such that firstArray[i] = firstArray[i] +
secondArray[i] where 0 <= i <= 4.
int[] sumEqualLengthArrays(int[] a, int[] b) {
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++)
result[i] = a[i] + b[i];
return result;
}
I have been stuck on this for a while now and I just can't get my head around what the answer is. I have attempted to answer it in the code above. I am a beginner to C++ programming as I am studying it in my free time. An answer to this question would really help!
Since you said you can use anything, Use std::vector with std::transform and std::plus<int>(). something like this :
std::transform (a.begin(), a.end(), b.begin(), a.begin(), std::plus<int>());
If you insist on using normal arrays (here assume a and b are arrays) then you can do something like this :
std::transform(a, &a[number_of_elements], b, a, std::plus<int>());
But please, don't.. Use std::vector.
How to use first approach :
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> a = {1, 2, 3};
std::vector<int> b = {1, 2, 3};
std::transform(a.begin(), a.end(), b.begin(), a.begin(), std::plus<int>());
for(auto iter = a.begin(); iter != a.end(); ++iter)
{
std::cout << *iter << std::endl;
}
return 0;
}
How to use second approach :
#include <iostream>
#include <algorithm>
int main()
{
int a[3] = {1, 2, 3};
int b[3] = {1, 2, 3};
std::transform(a, &a[0] + 3, b, a, std::plus<int>());
for(int i = 0; i < 3; ++i)
{
std::cout << a[i] << std::endl;
}
return 0;
}
Something like this:
std::vector<int> sumEqualLengthArrays(const std::vector& rhs,
const std::vector& lhs){
if(lhs.length() == rhs.length()){
std::vector<int> result(rhs.length(), 0);
for(unsigned int i = 0; i < rhs.length; ++i){
result[i] = rhs[i] + lhs[i];
}
return result;
}else{
std::cout << "Length is not equal!" << std::endl;
return rhs;
}
}
I would advise to use vectors instead of arrays and check the length before usage just in case to avoid errors.
You've written the summing expression already in the problem formulation. If you look at it once again, you'll see that the result is stored in first and there's no need in separate result array (returning an array is not a trivial thing in C++).
And, speaking of which, passing arrays as arguments is not easy either.
Assuming, you don't use std::vector, simple options are as follows.
int a[] (note the position of square brackets) as a function formal argument is synonymous to a pointer. It does not contain any size information, so you'll have to add a third argument which is the minimal size of both arrays:
int *add(int a[], int b[], std::size_t commonSize) { // commonSize is the least of a's and b's sizes
for(std::size_t i = 0; i < commonSize; ++i) a[i] += b[i];
return a;
}
You can deduce array's size when passed by reference, this is allowed in C++ and is a serious deviation from classic C:
template<std::size_t A, std::size_t B> int (&add(int (&a)[A], int (&b)[B]))[A] {
for(std::size_t i = 0; i < std::min(A, B); ++i) a[i] += b[i];
return a;
}
Then the common size is the minimum of A and B.
You can use std::array, this is almost the same as previous option
template<std::size_t A, std::size_t B> void add(std::array<int, A> &a, std::array<int, B> const &b);
This way you can even use range-for loops, or, for instance, STL algorithms (which tend to acquire parallelized and non-sequential overloads recently), though it requires a small amount of additional work (which is a bit too large to fit in this margin).
I am trying to write a program with a function double_product(vector<double> a, vector<double> b) that computes the scalar product of two vectors. The scalar product is
$a_{0}b_{0}+a_{1}b_{1}+...+a_{n-1}b_{n-1}$.
Here is what I have. It is a mess, but I am trying!
#include <iostream>
#include <vector>
using namespace std;
class Scalar_product
{
public:
Scalar_product(vector<double> a, vector<double> b);
};
double scalar_product(vector<double> a, vector<double> b)
{
double product = 0;
for (int i = 0; i <= a.size()-1; i++)
for (int i = 0; i <= b.size()-1; i++)
product = product + (a[i])*(b[i]);
return product;
}
int main() {
cout << product << endl;
return 0;
}
Unless you need to do this on your own (e.g., writing it is homework), you should really use the standard algorithm that's already written to do exactly what you want:
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<double> a {1, 2, 3};
std::vector<double> b {4, 5, 6};
std::cout << "The scalar product is: "
<< std::inner_product(std::begin(a), std::end(a), std::begin(b), 0.0);
return 0;
}
Note that while begin(a) and end(a) are new in C++11, std::inner_product has been available since C++98. If you are using C++ 98 (or 03), it's pretty easy to write your own equivalent of begin and end to work with arrays though:
template <class T, size_t N>
T *begin(T (&array)[N]) {
return array;
}
template <class T, size_t N>
T *end(T (&array)[N]) {
return array + N;
}
Using these, a C++ 98 version of the previous code could look something like this:
int main() {
double a[] = {1, 2, 3};
double b[] = {4, 5, 6};
std::cout << "The scalar product is: "
<< std::inner_product(begin(a), end(a), begin(b), 0.0);
return 0;
}
Note that the begin and end above will only work for arrays, where the begin and end in C++11 (and later) will also work for normal collection types that define a .begin() and .end() (though it's trivial to add overloads to handle those as well, of course):
template <class Coll>
typename Coll::iterator begin(Coll const& c) { return c.begin(); }
template <class Coll>
typename Coll::iterator end(Coll const& c) { return c.end(); }
You can delete the class you have defined. You don't need it.
In your scalar_product function:
double scalar_product(vector<double> a, vector<double> b)
{
double product = 0;
for (int i = 0; i <= a.size()-1; i++)
for (int i = 0; i <= b.size()-1; i++)
product = product + (a[i])*(b[i]);
return product;
}
It's almost there. You don't need 2 loops. Just one.
double scalar_product(vector<double> a, vector<double> b)
{
if( a.size() != b.size() ) // error check
{
puts( "Error a's size not equal to b's size" ) ;
return -1 ; // not defined
}
// compute
double product = 0;
for (int i = 0; i <= a.size()-1; i++)
product += (a[i])*(b[i]); // += means add to product
return product;
}
Now to call this function, you need to create 2 vector objects in your main(), fill them with values, (the same number of values of course!) and then call scalar_product( first_vector_that_you_create, second_vector_object );
While you have been presented many solutions that work, let me spin up another variation to introduce a couple of concepts that should help you writing better code:
class are only needed to pack data together
a function should check its preconditions as soon as possible, those should be documented
a function should have postconditions, those should be documented
code reuse is the cornerstone of maintenable programs
With that in mind:
// Takes two vectors of the same size and computes their scalar product
// Returns a positive value
double scalar_product(std::vector<double> const& a, std::vector<double> const& b)
{
if (a.size() != b.size()) { throw std::runtime_error("different sizes"); }
return std::inner_product(a.begin(), a.end(), b.begin(), 0.0);
} // scalar_product
You could decide to use the inner_product algorithm directly but let's face it:
it requires four arguments, not two
it does not check for its arguments being of the same size
so it's better to wrap it.
Note: I used const& to indicate to the compiler not to copy the vectors.
You seem to want to make a class specifically for vectors. The class I made in my example is tailored to 3 dimensional vectors, but you can change it to another if desired. The class holds i,j,k but also can conduct a scalar products based on other MathVectors. The other vector is passed in via a C++ reference. It is hard to deduce what the question was, but I think this might answer it.
#include <iostream>
using namespace std;
class MathVector
{
private:
double i,j,k;
public:
MathVector(double i,double j,double k)
{
this->i=i;
this->j=j;
this->k=k;
}
double getI(){return i;}
double getJ(){return j;}
double getK(){return k;}
double scalar(MathVector &other)
{
return (i*other.getI())+(j*other.getJ())+(k*other.getK());
}
};
int main(int argc, char **argv)
{
MathVector a(1,2,5), b(2,4,1);
cout << a.scalar(b) << endl;
return 0;
}
Here is the code that you should have. I see you have used class in your code, which you do not really need here. Let me know if the question required you to use class.
As you are new and this code might scare you. So, I will try to explain this as I go. Look for comments in the code to understand what is being done and ask if you do not understand.
//Scalar.cpp
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
/**
This function returns the scalar product of two vectors "a" and "b"
*/
double scalar_product(vector<double> a, vector<double> b)
{
//In C++, you should declare every variable before you use it. So, you declare product and initialize it to 0.
double product = 0;
//Here you check whether the two vectors are of equal size. If they are not then the vectors cannot be multiplied for scalar product.
if(a.size()!=b.size()){
cout << "Vectors are not of the same size and hence the scalar product cannot be calculated" << endl;
return -1; //Note: This -1 is not the answer, but just a number indicating that the product is not possible. Some pair of vectors might actually have a -1, but in that case you will not see the error above.
}
//you loop through the vectors. As bobo also pointed you do not need two loops.
for (int i = 0; i < a.size(); i++)
{
product = product + a[i]*b[i];
}
//finally you return the product
return product;
}
//This is your main function that will be executed before anything else.
int main() {
//you declare two vectors "veca" and "vecb" of length 2 each
vector<double> veca(2);
vector<double> vecb(2);
//put some random values into the vectors
veca[0] = 1.5;
veca[1] = .7;
vecb[0] = 1.0;
vecb[1] = .7;
//This is important! You called the function you just defined above with the two parameters as "veca" and "vecb". I hope this cout is simple!
cout << scalar_product(veca,vecb) << endl;
}
If you are using an IDE then just compile and run. If you are using command-line on a Unix-based system with g++ compiler, this is what you will do (where Scalar.cpp is the file containing code):
g++ Scalar.cpp -o scalar
To run it simply type
./scalar
You should get 1.99 as the output of the above program.
can someone please provide an example of how to use uBLAS product to multiply things? Or if there's a nicer C++ matrix library you can recommend I'd welcome that too. This is turning into one major headache.
Here's my code:
vector<double> myVec(scalar_vector<double>(3));
matrix<double> myMat(scalar_matrix<double>(3,3,1));
matrix<double> temp = prod(myVec, myMat);
Here's the error:
cannot convert from 'boost::numeric::ublas::matrix_vector_binary1<E1,E2,F>' to 'boost::numeric::ublas::matrix<T>'
I have exhausted my search. Stackoverflow has a question about this here. Boost documentation has an example here.
I've copied the code from example, but it's of no use to me because the template magic that works for stdout is useless to me.
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
int main () {
using namespace boost::numeric::ublas;
matrix<double> m (3, 3);
vector<double> v (3);
for (unsigned i = 0; i < std::min (m.size1 (), v.size ()); ++ i) {
for (unsigned j = 0; j < m.size2 (); ++ j)
m (i, j) = 3 * i + j;
v (i) = i;
}
std::cout << prod (m, v) << std::endl;
std::cout << prod (v, m) << std::endl;
}
The product of a vector and a matrix is a vector, not a matrix.
I haven't looked that much at Boost uBLAS, but Eigen sure is nice, and has good performance as well.