Gaussian elimination issue in solving the matrix - c++

float aMatrix[10][11];
float bMatrix[10];
// called as such...
solveMatrix(aMatrix, bMatrix, actualCol);
float* solveMatrix(float aMatrix[][DEFCOLS+1],float bMatrix[DEFCOLS], size_t cols){
std::cout << "\nInside solveMatrix...: " << endl;
size_t N2 = cols;
std::cout << "\N2 is...: " << N2 << endl;
for(size_t p=0; p<N2; p++){
//std::cout << "\nInside 1st for loop...: " << endl;
// find pivot row and swap
int max = p;
for(size_t i=p+1; i<N2; i++){
//std::cout << "\nInside 2nd for loop...: " << endl;
if ( abs(aMatrix[i][p]) > abs(aMatrix[max][p]) ){
max = i;
}
}
//std::cout << "\nJust b4 all the swapping...: " << endl;
float temp[] = { *aMatrix[p] };
*aMatrix[p] = *aMatrix[max];
*aMatrix[max] = *temp;
float t = bMatrix[p];
bMatrix[p] = bMatrix[max];
bMatrix[max] = t;
//std::cout << "\nDone all the swapping...: " << endl;
if ( abs(aMatrix[p][p]) <= MINISCULE) {
//std::cout << "***** Error matrix value too small. Matrix is singular" << endl;
//exit;
}
//std::cout << "\nJust the pivoting...: " << endl;
// Pivot /in A and b
for(size_t i=p+1; i<N2; i++){
//std::cout << "\nInside the 1st pivoting loop...: " << endl;
//std::cout << "\nAbout to do the [aMatrix[p][p]] division in back subst..: " << endl;
float alpha = aMatrix[i][p] / aMatrix[p][p];
bMatrix[i] = alpha * bMatrix[p];
for(size_t j=p; j<N2; j++){
//std::cout << "\nInside the 2nd pivoting loop...: " << endl;
aMatrix[i][j] -= alpha * aMatrix[p][j];
}
}
std::cout << "\nAbout to do the back subst..: " << endl;
// back subst.
float outMatrix[DEFROWS] = {0.0};
for(size_t i=N2-1; i>=0; i--){
std::cout << "\nInside the 1st back subst for loop..: " << endl;
float sum = 0.0;
for(size_t j=i+1; j<N2; j++){
std::cout << "\nInside the 2nd back subst for loop..: " << endl;
sum += aMatrix[i][j] * outMatrix[j];
}
std::cout << "\nAbout to do the [aMatrix[i][i]] division in back subst..: " << endl;
std::cout << "\n*outMatrix[i]: " << outMatrix[i] << endl;
std::cout << "\n( bMatrix[i] - sum ) : " << ( bMatrix[i] - sum ) << endl;
std::cout << "\n****aMatrix[i][i] : " << aMatrix[i][i] << endl;
if (aMatrix[i][i] > 0){
std::cout << "\nDid the division [aMatrix[i][i]] > 0 division in back subst..: " << endl;
std::cout << "\n*outMatrix[i]: " << outMatrix[i] << endl;
std::cout << "\n( bMatrix[i] - sum ) : " << ( bMatrix[i] - sum ) << endl;
std::cout << "\naMatrix[i][i] : " << aMatrix[i][i] << endl;
outMatrix[i] = ( bMatrix[i] - sum ) / aMatrix[i][i];
std::cout << "\nDid the division [aMatrix[i][i]] > 0 division in back subst..DONE: " << endl;
}else {
std::cout << "\nDid the divirion [aMatrix[i][i]] = 0 division in back subst..: " << endl;
outMatrix[i] = 0.0;
std::cout << "\nDid the divirion [aMatrix[i][i]] = 0 division in back subst..DONE: " << endl;
}
std::cout << "\nDid the [aMatrix[i][i]] division in back subst..: " << endl;
}
std::cout << "\nLeft the back subst for loops..: " << endl;
return outMatrix;
}
} // end solveMatrix()
My problem is that my program seems to run but seems to run past the end of the matrix and crashes. Plus I am getting some large exponential numbers and the largest numbers that I have in the array is from 1-10.
here is a screenshot of the output: Can't seem to paste from the snipping tool. But the problem seem to start after the "back substitution" starts.
Any help would be appreciated.

I am not sure what all the problems are, but one clear issue is your outMatrix. You are returning a pointer to a local array. The array is being destroyed at the end of the function. The pointer you are returning is now junk.
Change this line:
float outMatrix[DEFROWS] = {0.0};
To:
float* outMatrix = new float[DEFROWS];
Then you need to zero that out.
NOTE: It would be better if you used a vector<float> and returned that, but you wrote it with a raw pointer so I am answering with raw pointer. Raw pointers lead to memory leaks. They should be avoided when possible. With modern C++ it is rarely necessary to allocate a raw pointer.
EDIT:
See Effective C++ Item #31
EDIT2: Changing to use vector, if your compiler supports the move operators and constructors as defined in the C++11 standard, then returning a vector is a cheap operation.
std::vector<float> solveMatrix(/* Your arguments */)
{
std::vector<float> outMatrix(DEFROWS, 0.0);
// Your code
return outMatrix;
}

Related

Football tournament with matrix

I'm trying to make a football tournament in C++, in which the user inputs the name of the teams(8 teams) and then each team has to play with the other one 1 time. Firstly, I don't know how to read the team names, I mean I tried to use .getline or just cin of a char array, but then I need to put the teams into the matrix and after the final game my program should print the table. So there's the first question: how to read the names and basically make the program think they are numbers or does it work with just with names, no need to use int? And then the users inputs the result for every game, but here comes the hard part. After all the results have been introduced, the matrix rotates cyclic and then the result stored in the variables(you will see in code victory/losses) overwrites themselves, so at the end, I cannot print the right table. So that's the second question: How can I make them store to the right 'team' while they rotate? Sorry if I didn't quite explain very well how it works, hope you understand it. Cheers!
// FOOTBALL TOURNAMENT
int map[2][4];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << "map[" << i << "][" << j << "]= ";
cin >> map[i][j];
}
}
cout << "The map looks like this:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << map[i][j] << " ";
}
cout << endl;
}
map[0][0] = 1;
int temp = 0, temp2 = 0, temp3 = 0, temp4 = 0, temp5 = 0, temp6 = 0;
int a, b, c, d, e, f, g, h, round = 0;
int victory_m00(0), losses_m10(0), victory_m10(0), losses_m00(0), victory_m01(0), losses_m11(0), victory_m11(0), losses_m01(0);
int victory_m02(0), losses_m12(0), victory_m12(0), losses_m02(0), victory_m03(0), losses_m13(0), victory_m13(0), losses_m03(0);
do
{
// Insert result for every game
cout << "Enter the result of the first game between " << map[0][0] << " vs. " << map[1][0] << endl;
cin >> a >> b;
if (a > b) {
victory_m00++;
losses_m10++;
}
else if (a < b)
{
victory_m10++;
losses_m00++;
}
cout << "Enter the result of the first game between: " << map[0][1] << " vs. " << map[1][1] << endl;
cin >> c >> d;
if (c > d) {
victory_m01++;
losses_m11++;
}
else if (c < d)
{
victory_m11++;
losses_m01++;
}
cout << "Enter the result of the first game between: " << map[0][2] << " vs. " << map[1][2] << endl;
cin >> e >> f;
if (e > f) {
victory_m02++;
losses_m12++;
}
else if (e < f)
{
victory_m12++;
losses_m02++;
}
cout << "Enter the result of the first game between: " << map[0][3] << " vs. " << map[1][3] << endl;
cin >> g >> h;
if (g > h) {
victory_m03++;
losses_m13++;
}
else if (g < h)
{
victory_m13++;
losses_m03++;
}
round++;
// Map switching
temp = map[1][0];
map[1][0] = map[0][1];
temp2 = map[1][1];
map[1][1] = temp;
temp3 = map[1][2];
map[1][2] = temp2;
temp4 = map[1][3];
map[1][3] = temp3;
temp5 = map[0][3];
map[0][3] = temp4;
temp6 = map[0][2];
map[0][2] = temp5;
map[0][1] = temp6;
// Table calculating and printing ~ also this has to be outside the loop (but at first i wanted to print the table after every 'round'
cout << "This is how the table looks like after the " << round << " round: \n";
cout << map[0][0] << " has: " << victory_m00 << " victory(-ies) and " << losses_m00 << " loss-es!\n";
cout << map[0][1] << " has: " << victory_m01 << " victory(-ies) and " << losses_m01 << " loss-es!\n";
cout << map[0][2] << " has: " << victory_m02 << " victory(-ies) and " << losses_m02 << " loss-es!\n";
cout << map[0][3] << " has: " << victory_m03 << " victory(-ies) and " << losses_m03 << " loss-es!\n";
cout << map[1][0] << " has: " << victory_m10 << " victory(-ies) and " << losses_m10 << " loss-es!\n";
cout << map[1][1] << " has: " << victory_m11 << " victory(-ies) and " << losses_m11 << " loss-es!\n";
cout << map[1][2] << " has: " << victory_m12 << " victory(-ies) and " << losses_m12 << " loss-es!\n";
cout << map[1][3] << " has: " << victory_m13 << " victory(-ies) and " << losses_m13 << " loss-es!\n";
cout << endl;
cout << endl;
} while (map[0][1] != 2);
```

Runge Kutta and PGPLOT

Hi guys when I use this code (makefile not included) I am supposed to be getting two sinusoidal outputs graphed on the same set of axes but for some reason although the output data is accurate the graph is not. In face its not even a smooth curve, it has holes and cusps. Anyone have an idea as to why? Does it have something to do this the array I have written for the time axis? (Note beginner at coding)
#include <iostream>
#include <cmath>
#include <stdio.h>
#include "cpgplot.h"
//d2xdt2 = -(g/L)*sin(x)
//dwdt = -d2xdt2
//coeff = -(g/L)
//dxdt= w
float dxdt(float w)
{
return w;
}
float dwdt(float x, float coeff)
{
return coeff*sin(x);
}
int main(){
// Standard Variables
float wARR[5];
float xARR[5];
float tARR[5];
float w; //w = angular velocity
float x; //x = theta used in second order equation
float xo; //xo = theta initial
float wo = 0; //wo = initial angular velocity
float dt = 1; //h = step value
float g=9.8; //g = gravity
float L; //L = length of pendulum
float to = 0;
float t;
float time;
float kx1, kw1;
float kx2, kw2;
float kx3, kw3;
float kx4, kw4;
// Input Printing
std::cout << "\n";
std::cout << "Click ENTER key after each value. Please input: \n The initial angle (in decimal radians): "<<"\n";
std::cin >> xo;
std::cout << "The length of the pendulum (in meters)."<<"\n";
std::cin >> L;
std::cout << "\n";
// Specific Variable Declarations
float coeff=-(g/L);
//Checkpoint values
std::cout << "CHECKPOINT VALUES: ";
std::cout << "\n";
std::cout << "Confirming your initial angle is: " << xo << " radian(s)";
std::cout << "\n";
std::cout << "Confirming the length is: " << L << " meters(s)";
std::cout << "\n";
std::cout << "Confirming the gravity constant is: " << g << " meters/sec";
std::cout << "\n";
std::cout << "Coeff (-g/L): " << coeff;
std::cout << "\n";
std::cout << "\n";
std::cout << "Insert the time (in seconds) you want to learn some cool stuff about your pendulum: "<<"\n";
std::cin >> time;
std::cout << "\n";
//Array info and Runge Kutta
xARR[0] = xo;
wARR[0] = 0;
tARR[0] = 0;
time=time+1;
for (int i = 0; i < time ; i++){
x = xARR[i];
w = wARR[i];
t = tARR[i];
kx1=dt*dxdt(w);
kw1=dt*dwdt(x,coeff);
kx2=dt*dxdt(w+kw1*0.5);
kw2=dt*dwdt(x+kx1*0.5, coeff);
kx3=dt*dxdt(w+kw2*0.5);
kw3=dt*dwdt(x+kx2*0.5, coeff);
kx4=dt*dxdt(w+kw3);
kw4=dt*dwdt(x+kx3, coeff);
std::cout << "\n";
std::cout << "RUNGE KUTTA VALUES: at " << i << " second(s)" << "\n";
std::cout << "kx1: " << kx1 << "\n";
std::cout << "kx2: " << kx2 << "\n";
std::cout << "kx3: " << kx3 << "\n";
std::cout << "kx4: " << kx4 << "\n";
std::cout << "kw1: " << kw1 << "\n";
std::cout << "kw2: " << kw2 << "\n";
std::cout << "kw3: " << kw3 << "\n";
std::cout << "kw4: " << kw4 << "\n";
xARR[i+1] = xo + (1.0/6.0)*(kx1 + 2*kx2 + 2*kx3 + kx4);
wARR[i+1] = wo + (1.0/6.0)*(kw1 + 2*kw2 + 2*kw3 + kw4);
std::cout << "FINAL VALUES: at " << i << " second(s)" << "\n";
std::cout << "The angle is: " << x << " radian(s)";
std::cout << "\n";
std::cout << "The velocity is: " << w << " radians/s";
std::cout << "\n";
std::cout << "\n";
std::cout << "-----------------------------------------------------\n";
std::cout << "\n";
}
// Graphing with arrays
//To see the time dependence, let's suppose you have two arrays: one for w and one for x. Then the values x[i] and w[i] entry describe the position and velocity of your pendulum at time t_i.
// Open a plot window
if (!cpgopen("/XWINDOW")) return 1;
// Set-up plot axes
// M_PI is defined in cmath
cpgenv(0,time,-1,1,0,1);
// Label axes
cpglab("time", "angle", "RED = Angle BLUE = Velocity");
cpgsci(2); //RED
cpgline(10,tARR, xARR);
cpgsci(4); //BLUE
cpgline(10,tARR, wARR);
cpgclos();
}

Issue with code P: PP Drill 4

I've been doing a drill from a book entitled Programming: Principles and Practice Using C++ by Bjarne Stroustrup, and this drill (Chapter 4) primarily deals with vectors. When I run the program, it doesn't give me any output at all. There are no compilation errors though. Here's the code:
#include "std_lib_facilities.h"
int main()
{
vector<double> value;
vector<string> units;
double max_val=-100000, min_val=100000;
double temp, sum=0;
int no_of_inputs=0;
string unit;
int i=0;
cout << "\nEnter the first value: " << endl;
// inputs values and units and assign them in vector value and vector unit respectively.
while (cin >> temp >> unit){
++no_of_inputs;
cout << "Enter the next value: " << endl;
value.push_back(temp);
units.push_back(unit);
}
// converts cm, in and ft to m;
for (i==0; i<units.size(); ++i){
if (units[i]== "cm" || units[i]== " cm"){
value[i] = value[i]/100.0;
}else if (units[i]== "in" || units[i]== " in"){
value[i] = value[i]/2.5/100.0;
}else if (units[i]== "ft" || units[i]== " ft"){
value[i] = value[i]*12/2.5/100.0;
}else if (units[i]=="m" || units[i]== " m"){
}else cout << "\n\n" << value[i] << " " << units[i] << " is an incorrect input value.";
return 0;
}
// Identifies the max_value and the min_value. Also adds all values.
for (i==0; i<value.size(); ++i){
if (value[i]>max_val){
max_val=value[i];
}
if (value[i]<min_val){
min_val=value[i];
}
sum += value[i];
}
// outputs all values entered (converted to meters)
cout << "\nValues Entered:"<< endl;
sort(value);
for (i==0; i<value.size(); ++i){
cout << value[i] << " meters" << endl;
}
cout << "Total: " << sum << " meters" << endl;
cout << "Smallest value: " << min_val << endl;
cout << "Largest value: " << max_val << endl;
cout << "Total values entered: " << no_of_inputs << endl;
return 0;
}
Can anyone tell me why it is not working?
you have 2 mistakes. The main reason for terminating your program is here
else cout << "\n\n" << value[i] << " " << units[i] << " is an incorrect input value."; return 0;
you putting return in the first for loop. I guess you may think return is belong to else but because you don't use scope determiner {} only 1 instruction (cout) is belong to else and return is executed every time.
your second mistake is use i==0 instead of i=0 in for loops.
your correct code is this :
vector<double> value;
vector<string> units;
double max_val = -100000, min_val = 100000;
double temp, sum = 0;
int no_of_inputs = 0;
string unit;
int i = 0;
cout << "\nEnter the first value: " << endl;
//inputs values and units and assign them in vector value and vector unit respectively.
while (cin >> temp >> unit){
++no_of_inputs;
cout << "Enter the next value: " << endl;
value.push_back(temp);
units.push_back(unit);
}
//converts cm, in and ft to m;
for (i = 0; i<units.size(); ++i){
if (units[i] == "cm" || units[i] == " cm"){
value[i] = value[i] / 100.0;
}
else if (units[i] == "in" || units[i] == " in"){
value[i] = value[i] / 2.5 / 100.0;
}
else if (units[i] == "ft" || units[i] == " ft"){
value[i] = value[i] * 12 / 2.5 / 100.0;
}
else if (units[i] == "m" || units[i] == " m")
{
}
else
{
cout << "\n\n" << value[i] << " " << units[i] << " is an incorrect input value.";
return 0;
}
}
//Identifies the max_value and the min_value. Also adds all values.
for (i = 0; i<value.size(); ++i){
if (value[i]>max_val){
max_val = value[i];
}
if (value[i]<min_val){
min_val = value[i];
}
sum += value[i];
}
//outputs all values entered (converted to meters)
cout << "\nValues Entered:" << endl;
//sort(value);
for (i = 0; i<value.size(); ++i){
cout << value[i] << " meters" << endl;
}
cout << "Total: " << sum << " meters" << endl;
cout << "Smallest value: " << min_val << endl;
cout << "Largest value: " << max_val << endl;
cout << "Total values entered: " << no_of_inputs << endl;
return 0;

Using pointers to duplicate and grow an existing array

I am failing to reach expected output when testing my 'grow'and 'subArray' functions. I've tried dereferencing back and forth in the function and also in main(). I'm wondering if there's something wrong with my memory allocation that is causing the lapse. I am extremely stuck and was hoping someone could potentially see something that I am missing, thanks.
#include <iostream>
#include <iomanip>
using namespace std;
bool isSorted(int *arr, int size){
for(int index = 0; index < size - 1; index ++){
if(*(arr + index) > *(arr + index + 1)){
return false;
}
}
return true;
}
double chain (int totalInches, int *feet, int *inches){
*feet = totalInches/12;
*inches = totalInches%12;
return *(feet)*3.49 + *(inches)*.30;
}
int *grow (int *arr, int size){
int *newArray;
newArray = new int[size*2]; //alocate new array
for(int i = 0; i < size*2; i+=2){
*(newArray + i) = *(arr+i);
*(newArray + i + 1) = *(arr+i);
}
return newArray;
}
int *duplicateArray (int *array, int size) {
int *newArray;
if (size <= 0)
return NULL;
newArray = new int [size]; //allocate new array
for (int index = 0; index < size; index++){
newArray[index] = array[index]; //copy to new array
}
return newArray;
}
int *subArray( int *array, int start, int length){
int *result = duplicateArray(array,5);
return result;
}
void showArray( int *arr, int size){
for(int i = 0; i < size; i ++)
{
cout << *(arr + i) << " ";
}
}
int main(){
int size = 8;
int testArray[] = {1,2,3,4,5,6,7,8};
cout << "testing isSorted: " << endl;
cout << "test data array 1: ";
showArray(testArray, size);
cout << endl;
cout << "Expected result: true" << endl;
cout << "Actual result: " << boolalpha << isSorted(testArray, size);
cout << endl;
int testArray2[]= {8,7,6,5,4,3,2,1};
cout << "test data array 2: ";
showArray(testArray2, size);
cout << endl;
cout << "Expected result: false" << endl;
cout << "Actual result: " << boolalpha << isSorted(testArray2, size);
cout << endl << endl << endl;
int chainTest = 53;
cout << "Checking chain for 53 inches: " << endl;
cout << "Expected result: 15.46 " << " " << "feet: 4 " <<
" " << "inches: 5"<< endl;
int in;
int ft;
cout << "Actual results : " << chain(chainTest,&ft,&in);
cout << " " << "feet: " << ft << " " << "inches: " << in << endl;
cout << endl << endl;
cout << "testing grow: " << endl;
cout << "test data 1: ";
showArray(testArray, size);
cout << endl;
cout << "Expected result: 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 " << endl;
cout << "Actual results: " << *(grow(testArray, size));
cout << endl << endl;
cout << "testing subArray:" << endl;
cout << "test data: ";
showArray(testArray, size);
cout << endl;
int start = 5;
int length = 3;
cout << "start: " << start << " " << "length: " << length << endl;
cout << "Expected result: " << "6 7 8" << endl;
cout << "Actual result: " << *(subArray(testArray, start, length));
cout << endl;
return 0;
}
Output:
As you notice, the loop is terminating after one traversal. The grow function is intended to duplicate and expand. In other words, it's supposed to make a copy of itself and append as it traverses. Any ideas as to why I am getting hung on the first element of the array?
You are actually doubling the array but only the first element is being printed because you are dereferencing an int* . To print all the elements, write a loop and print all the elements.
Also there is so much memory leak here. Please free memory after you are done using it. You are read about the delete[] operator.
Your loop going two at a time is good but it prevents you from selecting every element in the original array causing you to skip the even numbers. check your for loop and consider using two counters or if you want to modify your for loop to
for(int i = 0; i < size*2; i+=2){
*(newArray + i) = *(arr+i/2);
*(newArray + i + 1) = *(arr+i/2);
}
to ensure every element is reached
also as stated in the comments, use the showArray method you implemented
showArray(grow(testArray, size),size*2);

trying to order 3 values from least to greatest C++

I have a program that takes numbers that a person enters and sums it.
This happens 3 times, so I have 3 totals. The problem I am having is that I need to order them from greatest to least no matter what the sums come out to be.(this isnt the full code assume the sums are calculated and are declared)
#include <iostream>
#include <string>
using namespace std;
string firstName1, lastName1; // input and output for the users names
string firstName2, lastName2;
string firstName3, lastName3;
// from greatest to least
if ( sum > sum_2 > sum_3 )
{
cout << "Total for" << " " << firstName1 << " " << lastName1 << " " << "$" << sum << ".00" << endl;
cout << "Total for" << " " << firstName2 << " " << lastName2 << " " << "$" << sum_2 << ".00" << endl;
cout << "Total for" << " " << firstName3 << " " << lastName3 << " " << "$" << sum_3 << ".00" << endl;
}
In c++, the syntax sum > sum_2 > sum_3 won't evaluate as you're assuming. It's equivalent to (sum > sum_2) > sum_3.
In the case where sum is greater than sum_2, sum > sum_2 will evaluate to true. Then, this boolean value will be converted to an integer, 1 and compared with sum_3.
To do what you're trying to accomplish try:
if (sum > sum_2 && sum_2 > sum_3)
Use a helper swap function:
void swap( int *a, int *b )
{
int temp = *a;
*a = *b;
*b = temp;
}
And bubble sort it:
int sums[3] = { sum, sum_2, sum_3 };
for ( int i = 0; i < 3; ++i )
for ( int j = 0; j < i; ++j )
if ( sums[j] < sums[i] )
swap( &sums[j], &sums[i] );
cout << "Total for" << " " << firstName1 << " " << lastName1 << " " << "$" << sums[0] << ".00" << endl;
cout << "Total for" << " " << firstName2 << " " << lastName2 << " " << "$" << sums[1] << ".00" << endl;
cout << "Total for" << " " << firstName3 << " " << lastName3 << " " << "$" << sums[2] << ".00" << endl;