std::vector<float> a {-0.2, 2.0, -0.9, 2.4, 22.0}
How to take absolute value of all vector elements?
The result should be
{0.2, 2.0, 0.9, 2.4, 22.0}
std::vector<float> a {-0.2, 2.0, -0.9, 2.4, 22.0}
How to take absolute value of all vector elements?
The result should be
{0.2, 2.0, 0.9, 2.4, 22.0}
this code will help you, loop the vector and apply abs (function to find absolute value )
for(unsigned int i = 0; i < numbers.size(); i++)
{
if(numbers[i] < 0)numbers[i] *= -1; //make positive. _OR_ use numbers[i] = abs(numbers[i]);
std::cout<<numbers[i]<<std::endl;
}
Use the formula |a| = sqrt(sum(ai*ai))
:
float value = 0.0;
for(int i = 0; i < a.size(); i++) value += a[i] * a[i];
value = sqrt(value);
You can use following code.
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
using namespace std;
void v_abs( vector <int> &x, double p[])
{
int i=0;
while( p[i] < x.size () )
{
if ( p[i] < 0 )
{
p[i] *= -1 ;
}
i ++;
}
}
int main() {
cout << v_abs << endl;
system("pause");
return 0;
}
You create a function that receives as input the vector and returns another vector:
const std::vector< float >& absValues(std::vector< float >& vecIn)
{
for(float &val : vecIn)
{
if (val < 0)
{
val *= -1;
}
}
return vecIn;
}
And if you want the sqrt of the sum of all elements of the vector, then you should do it as John Bupit said (IMHO is nice)