C++ 2D array table - c++

I'm trying to create an 2D array table in C++ with a for loop and this is my code below.
//receive user input
double nSideA = sSideA;
for( double x = nSideA; x < eSideA; x = x + incrementA){
cout << "a=" << fixed << setprecision(1) << setw(4) << nSideA << " ";
nSideA += incrementA;
} // table header
cout << "\n"; //spacing
for (double y = sSideB; y < eSideB; y = y + incrementB){
for( double x = sSideA; x < eSideA; x = x + incrementA){
sSideA += incrementA;
sSideB += incrementB;
hypo = sqrt( pow(sSideA,2) + pow(sSideB,2) );
cout << "b=" << fixed << setprecision(1) << setw(4) << sSideB << " ";
cout << fixed << setprecision(3) << setw(3) << hypo << " " << endl;
}} // content
My output for the table is something like :
b= 2.0 2.828
b= 3.0 4.243
b= 4.0 5.657
b= 5.0 7.071
b= 6.0 8.485
b= 7.0 9.899
with b not looping properly. (Printed all in a column thanks to Frax in the comments with endl;)
This is supposed to be a program that performs the Pythagoras Theorem. I intend for my output to be like
However, the results go wrong on the second loop where a[1][1] ends up at a[1][0] , a[2][2] ends up at a[2][0] and so on.
How do I fix my for loop to make it print a proper table?
Thank you.

Related

Output value of array rather than memory address of array

So I've made a basic polynomial class in C++ which stores the coefficients of these polynomials dynamically on the heap. I'm currently in the process of overloading operators so that I can add/subtract polynomials together in order to simplify them etc.
However I'm getting unexpected results when I try to overload the * operator. It looks like instead of returning the value of an index in the array it is returning the position of the array.
This is my *operator method in my .cpp file:
Polynomial Polynomial::operator*(Polynomial p) {
int maxDegree = (degree)+(p.degree - 1);
int *intArray3 = new int[maxDegree];
int i, j;
for (int i = 0; i < degree; i++) {
for (int j = 0; j < p.degree; j++) {
cout << getCoef(i) << " * " << p.getCoef(j) << " = " << getCoef(i)*p.getCoef(j) << endl;
intArray3[j] += (getCoef(i))*(p.getCoef(j));
cout << " intArray3[" << j << "] contains : " << intArray3[j] << endl;
}
}
return Polynomial(maxDegree, intArray3);}
The lines:
cout << getCoef(i) << " * " << p.getCoef(j) << " = " << getCoef(i)*p.getCoef(j) << endl;
and
cout << " intArray3[" << j << "] contains : " << intArray3[j] << endl;
return
10 * 1 = 10
intArray3[0] contains : -842150441
in my console. I'm assuming that the problem lies with my use of pointers somewhere but I can't for the life of me think why. I implemented this overload in a similar way to my + and - overloads and they work fine. Any assistance would be greatly appreciated. Cheers.

Reverse a set of points in c++

I need to generate points around a quarter circle in the anticlockwise direction but with my program I'm able to generate in clockwise direction. Below is my code.
#include <iostream>
#include <cmath>
#include <fstream>
#include <iomanip>
using namespace std;
int main ()
{
int NumberPoints(10);
double x1;
const double PI = 3.14159;
double radius = 5;
double angle = 0.7853; //45 degrees
ofstream plot;
string plotDataFile("points.txt");
plot.open(plotDataFile.c_str());
for (int i = 0; i <= NumberPoints; i++)
{
x1 = angle/NumberPoints*i;
plot << setprecision(5) << radius * sin(x1) << " ";
plot << setprecision(5) << radius * cos(x1) << " " << endl;
}
plot.close();
}
I get the following output.
0 5
0.39225 4.9846
0.78208 4.9385
1.1671 4.8619
1.5449 4.7553
1.9132 4.6195
2.2697 4.4552
2.6122 4.2634
2.9386 4.0453
3.2469 3.8023
3.5352 3.5359
I need points in the format
3.5352 3.5359
3.2469 3.8023
2.9386 4.0453
.
.
0 5
Could someone help me modify my code or give me an idea for the same.
How about this?
for (int i = NumberPoints; i >= 0; i--)
{
x1 = angle/NumberPoints*i;
plot << setprecision(5) << radius * sin(x1) << " ";
plot << setprecision(5) << radius * cos(x1) << " " << endl;
}
Instead of
for (int i = 0; i <= NumberPoints; i++)
use
for (int i = NumberPoints; i >= 0; i--)
just iterate backwards:
for (int i = NumberPoints; i >= 0; i--)
By the way, your variable NumberPoints has probably wrong name. Notice that you are getting 11 points, not 10.
may be help
Input:
0 5
0.39225 4.9846
0.78208 4.9385
std::vector< std::pair< std::string, std::string > > pair_of_point;
pair_of_point.emplace_back("0", "5");
pair_of_point.emplace_back("0.39225", "4.9846");
pair_of_point.emplace_back("0.78208", "4.9385");
std::reverse( pair_of_point.begin(), pair_of_point.end()) ;
std::cout << pair_of_point[ 0 ].first << " " << pair_of_point[ 0 ].second << std::endl;
std::cout << pair_of_point[ 1 ].first << " " << pair_of_point[ 1 ].second << std::endl;
std::cout << pair_of_point[ 2 ].first << " " << pair_of_point[ 2 ].second << std::endl;
output
0.78208 4.9385
0.39225 4.9846
0 5
Instead of std::string enter you date-type

sparse matrix-matrix / matrix-vector multiplication c++

I'm using eigen3 package in c++ to do some linear algebra, but one part of the code which includes some matrix-matrix and matrix-vector multiplications takes too long. my matrices and vectors are pretty big (order 20kx20k) but some are sparse. what I read from eigen documentation, it is designed to be working efficiently with sparse matrices. I don't know what I'm doing wrong or how I can improve it. Would appreciate any help.
Here is part of the code; we have n input data for which we calculate 'k' from a function and for each point we need to find a 'mean' value defined in the code:
#pragma omp parallel for ordered schedule(dynamic)
for (unsigned long n = 0; n < nNew; n++) {
SparseVector<double> kJ(totalJ);
double k = something; #calculates using a function
for(int i=0; i<totalJ; i++) {
double covTmp = xxx; #calculates using a function
kJ.insert(i) = covTmp;
}
SparseVector<double> CJikJ(totalJ);
CJikJ = CJi * kJ;
double kJTCJikJ = kJ.transpose().dot(CJikJ);
double mu = 1. / (k - kJTCJikJ);
SparseVector<double> mJ(totalJ);
mJ= -mu * CJikJ;
SparseMatrix<double> MJi(totalJ, totalJ);
MJi = CJ - kJ*kJ.transpose()*mu / (1. + mu * kJTCJikJ);
SparseMatrix<double> VNGJMJiGJTi(nstars, nstars);
VNGJMJiGJTi = invertMatrix(VN + GJ * (MJi * GJT), nstars);
SparseMatrix<double> RJi(totalJ, totalJ);
RJi = MJi - MJi * GJT * (VNGJMJiGJTi) * (GJ * MJi); ## this line takes too long
RJi.prune(prunelim);
SparseVector<double> RJimJ;
RJimJ = RJi*mJ;
double alpha = mu - mJ.dot(RJimJ);
double beta = AN.dot((VNi * GJ) * RJimJ);
double mean = -beta / alpha;
outfile << setprecision(8) << newposm[n][0] << ", " << newposm[n][1] << ", " << newposm[n][2] << ", " << alpha << ", " << beta << ", " << mean << ", " << variance << "\n";
if(params.vb) {
cout << setprecision(8) << "# l, b, dist, alpha, beta, mean, var" << endl;
cout << setprecision(8) << newposm[n][0] << ", " << newposm[n][1] << ", " << newposm[n][2] << ", " << alpha << ", " << beta << ", " << mean << ", " << variance << "\n";
}
}

How to access to the values stored in a flann::Matrix

I'm working with flann library with point clouds. I have this adapter method that transform my own points to a flann-usable points
flann::Matrix<float> * converterFlann::convertArray(vector<Point *> *P){
float points[P->size()*3];
int j = 0;
for (int i = 0; i<P->size(); i++){
points[j] = P->at(i)->getX(); j++;
points[j] = P->at(i)->getY(); j++;
points[j] = P->at(i)->getZ(); j++;
}
P->at(0)->print();
cout << points[0] << " " << points[1] << " " << points[2] << endl;
flann::Matrix<float> *nari = new flann::Matrix<float>(points, P->size(), 3);
cout << *nari[0][0] << " " << *nari[0][1] << " " << *nari[0][2] << endl;
return nari;
}
And the output of this method is
Printing my point: (-0.06325, 0.0359793, 0.0420873) Index: 0
Printing from points array: -0.06325 0.0359793 0.0420873
Printing from flann: -0.06325 -0.06275 -0.0645
I don't understand why printing from flann::Matrix, Y and Z are different. I've been looking for some documentation about storing procedure of flann::Matrix but I'm not able to find any answer. I thing that my array-type access is correct but it doesn't work.
Thanks in advance. :D

C++ how to load a 16bit TIFF file in a container to perform math operations on its data?

I have writtent a small C++ console application with code::blocks that loads
an array of values from a CSV file, performs a special "inverted" random dithering on the values, and exports the result as a PBM file (a bitmap).
The density of black pixels on the final PBM picture depends on 3 independent variables: "Reflectance of the white", "Reflectance of the black", and the values of the CSV.
The reason I use a CSV file is because I don't know how I can directly load a TIFF file into my script. The values of my file "wall.csv" are produced by a python script that transforms any tiff file in a csv...
Could you please check my code and advise for a solution to load a TIFF and detect automatically the size of the image in pixels?
The variables colo and lines define the size of the image contained as ASCII data in the CSV...
And the image values are loaded in the vector <float> CSV
What library would you use to load the tiff?
Thanks!
code:
#include <deque>
#include <cmath>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <random>
#include <cstdlib>
using namespace std;
deque <float> CSV; // CSV input values, "PHOTOMETRY"
deque <float> RND; // will contain random values from 0.0 to 1.0
int colo = 0; // variables inputed
int lines = 0; // lines
float YBK = 0; // Reflectance White
float YW = 0; // Reflectance Black
float Lmax = 0; // variables to be computed
float Lmin = 10000000; // arbitrarily high value
float NBK = 0; // will contain a normalized Black value
float NW = 1; // normalized white value
float CRATIO = 0; // Black to White dynamic ratio
float LRATIO = 0; // Lowest to Highest pixel value dynamic ratio
float Z = 0; // processing variables
float X = 0;
float aBK = 0; // computed density of black at each pixel
float vRND = 0; // random value container
float IO = 0;
int main(){
cout << "please put a file named wall.csv" << endl << "in the same forler as this executable" << endl << endl;
cout << "how many:" << endl << "columns does the CSV has?" << endl;
cin >> colo;
cout << "lines does the CSV has?" << endl;
cin >> lines;
cout << "reflectance of the WHITE (CIE Y)?" << endl;
cin >> YW;
cout << "reflectance of the BLACK (CIE Y)?" << endl;
cin >> YBK;
NBK = YBK / YW; // normalized BK
CRATIO = NW / NBK; // correction Ratio
int C = lines * colo; // cells
cout << endl << " there are: " << colo << " columns";
cout << endl << " and : " << lines << " lines " ;
cout << endl << " that makes " << C << " cells " << endl;
cout << endl << " correction ratio is: " << CRATIO << endl << endl;
///_____ IMPORT THE PHOTOMETRIC DATA
cout << "...importing the photometric data" << endl;
float x = 0; // a variable that will contain a value from the file
ifstream ifs ("wall.csv");
char dummy;
for (int i = 0; i < lines; ++i){
for (int i = 0; i < colo; ++i){
ifs >> x;
if (x > Lmax) {
Lmax = x; // determines the highest pixel value
}
if (x < Lmin) {
Lmin = x; // determines the lowest pixel value
}
CSV.push_back(x);
// So the dummy won't eat digits
if (i < (colo - 1))
ifs >> dummy;
}}
ifstream ifs_close();
LRATIO = Lmax / Lmin;
cout << "...photometric data imported" << endl;
cout << endl << " maximum Luminance is: " << Lmax;
cout << endl << " minimum Luminance is: " << Lmin << endl;
cout << endl << "...luminance ratio is: " << LRATIO;
if (LRATIO > CRATIO) {
cout << endl << "...luminance ratio is: " << LRATIO;
cout << endl << "...this is too high, ending..." << '\a';
return(0);
}
cout << endl << "...luminance can be corrected :)" << endl;
///______ CREATE RANDOM VALUES BETWEEN 0 & 1
std::default_random_engine generator;
std::uniform_real_distribution <double> distribution(0.0,1.0);
for (int i=0; i<C; ++i) {
double number = distribution(generator);
RND.push_back(number);
}
cout << endl << "...random values created" << endl;
///_______ process & export to PBM
ofstream output_file("./wall.pbm");
output_file << "P1" << "\n" << colo << " " << lines << "\n"; /// PBM HEADER
cout << endl << "...file header written" << endl;
cout << endl << "...computing";
int CELLS = C; // copy the amount of cells
int LINEW = colo;
int PERCENT = 100;
while (CELLS > 0) {
while (LINEW > 0) {
Z = Lmin/CSV.front(); /// processing calculus
X = (NBK - Z)/(NBK - NW);
aBK = (1 - X);
vRND = RND.front();
if (aBK > (vRND)) {
IO = 1;
}
else {
IO = 0;
}
LINEW = LINEW - 1;
CELLS = CELLS - 1;
PERCENT = PERCENT - CELLS / C;
output_file << IO << "\n";
//cout << ERR << " "; /// fancy...
CSV.erase(CSV.begin());
RND.erase(RND.begin());
}
LINEW = colo;
}
cout << endl << "...computing done" << endl;
cout << "...file written";
output_file.close();
return(0);
}
Check out lib tiff. OpenCV just uses lib tiff as well.
http://www.libtiff.org/