So I'm trying to read a matrix A from a text file, which it does correctly. A vector B is entered by the user. Then I want to perform Gaussian Elimination (Ax = b) to get the solution vector x. The values I get for x are -1.#IND and I have no idea why...I'm guessing something is going wrong in SystemSolution?
#include <iostream>
#include <vector>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
//this program does gaussian elimination for a matrix Ax=b
vector<double> SystemSolution(vector<vector<double>> A, vector<double> b)
{
//Determine and test size of a matrix
int n = A.size();
for (int i = 0; i < n; i++)
if (n != A[i].size())
throw "Error! Number of rows and columns of matrix must be equal!";
vector<double> x(b.size());
//x is the vector of solutions
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
//Finding pivot
double pivot = A[i][i];
int index = i;
for (int k = i + 1; k < n; k++)
{
if (pivot > abs(A[k][i]))
{
index = k;
pivot = A[k][i];
}
}
//Row exchange
for (int k = 0; k < n; k++)
{
double tmp = A[i][k];
A[i][k] = A[index][k];
A[index][k] = tmp;
}
//Elimination
double coefficient = -(A[j][i] / A[i][i]);
for (int k = i; k < n; k++)
{
A[j][k] += coefficient*A[i][k];
}
b[j] += coefficient*b[i];
}
}
//Back-substitution
x[n - 1] = b[n - 1] / A[n - 1][n - 1];
for (int i = n - 2; i >= 0; i--)
{
double sum = 0;
for (int j = i; j < n; j++)
{
sum += x[j] * A[i][j];
}
x[i] = (b[i] - sum) / A[i][i];
}
return x;
}
void PrintVector(const vector<double> &b)
{
for (int i = 0; i < b.size(); i++)
cout << setiosflags(ios::showpoint | ios::fixed | ios::right)
<< setprecision(4)
<< setw(8) << b[i] << endl;
}
void PrintMatrix(const vector<vector<double> > &A)
{
for (int i = 0; i < A.size(); i++)
{
for (int j = 0; j < A[i].size(); j++)
cout << setiosflags(ios::showpoint | ios::fixed | ios::right)
<< setprecision(4)
<< setw(8) << A[i][j];
cout << endl;
}
}
int main()
{
int n;
cout << "Please enter the number of rows/columns:";
cin >> n;
ifstream matrixFile;
matrixFile.open("matrix.txt");
if (matrixFile.is_open()){
//matrix A values
vector<vector<double>> A(n, vector<double>(n));
vector<double> b(n);
string line;
int col = 0;
int row = 0;
while (getline(matrixFile, line)){
istringstream stream(line);
int x;
col = 0; //reset
while (stream >> x){
A[row][col] = x;
col++;
}
row++;
}
cout << "Please enter vector b:"<<endl;
//vector b values
for (int i = 0; i < row; i++)
{
cout << "b[" << i + 1 << "]= ";
cin >> b[i];
}
vector<double> x = SystemSolution(A, b);
cout << "- SOLUTIONS -" << endl;
cout << "Matrix:" << endl;
PrintMatrix(A);
cout << "\nVector x:" << endl;
PrintVector(x);
}
else{
cout << "File failed to open!";
}
matrixFile.close();
return 0;
}
There could be some divisions by zero in your code:
double coefficient = -(A[j][i] / A[i][i]);
/* .. */
x[n - 1] = b[n - 1] / A[n - 1][n - 1];
/* .. */
x[i] = (b[i] - sum) / A[i][i];
Check out Gauss-elimination here:
Square Matrix Inversion in C
Review and debug yours.
Related
I have this task:
A user inputs a number N and you have to output this pyramid:
0
101
21012
.......
N.21012.N
For N=5 it will be :
0
101
21012
3210123
432101234
54321012345
I managed to only get it working for N<10 with this code:
int n;
cin >> n;
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < n - i; j++)
cout << " ";
int dir = -1;
for (int k = i; k <= i; k += dir) {
cout << k;
if (k == 0)
dir = 1;
}
cout << endl;
}
For N=10 it will look like this :
0
101
21012
3210123
432101234
54321012345
6543210123456
765432101234567
87654321012345678
9876543210123456789
10987654321012345678910
After the answers I settled on this :
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
int n, spaces;
string number;
cin >> n;
if (n < 10)
spaces = n;
else
{
spaces = 9;
int pwr = 0, k = n;
while (k > 9)
{
pwr++;
k /= 10;
}
for (int i = 1; i < pwr; i++)
{
spaces += pow(10, i) * 9 * (i + 1);
}
spaces += (n - pow(10, pwr) + 1) * (pwr + 1);
}
// cout << spaces << endl;
for (int i = 0; i < n + 1; i++)
{
for (int j = i; j > -1; j--)
number += to_string(j);
int len = number.length() - 1;
for (int j = 0; j < spaces - len; j++)
cout << " ";
for (int j = 1; j <= i; j++)
number += to_string(j);
cout << number << endl;
number.clear();
}
cout << endl;
return 0;
}
int padding(int n) {
constexpr auto singleDigitNumbersCount = 9;
constexpr auto doubleDigitNumbersCount = 90; // from 10 to 99
if (n < 10) return n;
if (n < 100) return 2*n - singleDigitNumbersCount;
return 3*n - doubleDigitNumbersCount - 2*singleDigitNumbersCount;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n + 1; i++) {
std::cout << std::string(padding(n) - padding(i), ' ');
for (int k = i; k >= 0; k--) {
cout << k;
}
for (int k = 1; k <= i; k++) {
cout << k;
}
cout << '\n';
}
return 0;
}
https://godbolt.org/z/EEaeWEvf4
I made this a bit ago Compiler Explorer
Not sure if that'd help 🤔
Here is the working code:
#include <string>
#include <iostream>
using namespace std;
#define MAX_SPACE 50
int main()
{
int n;
cin >> n;
string output = "";
for (int i = 0; i < n + 1; i++)
{
for (int k = i; k >= 0; k--) {
output += to_string(k);
}
for (int k = 1; k <= i; k++) {
output += to_string(k);
}
for (uint8_t i = 0, max = MAX_SPACE - output.length() / 2.00; i < max; i++) // Print max spaces minus the integer length divided by 2
{
cout << " ";
}
cout << output << endl; // Print number
output = "";
}
return 0;
}
My program counts the determinant of a matrix.
square matrix size = 3
source
the matrix
1 2 3
4 5 6 -> и вычесть из каждого элемента главной диагонали X
7 8 9
1-x 2 3
4 5-x 6 ->решить определитель
7 8 9-x
#include<iostream>
#include<math.h>
using namespace std;
int determinant(int matrix[10][10], int n) {
int det = 0;
int submatrix[10][10];
if (n == 2)
return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));
else {
for (int x = 0; x < n; x++) {
int subi = 0;
for (int i = 1; i < n; i++) {
int subj = 0;
for (int j = 0; j < n; j++) {
if (j == x)
continue;
submatrix[subi][subj] = matrix[i][j];
subj++;
}
subi++;
}
det = det + (pow(-1, x) * matrix[0][x] * determinant(submatrix, n - 1));
}
}
return det;
}
int main() {
int n, i, j,x;
int matrix[10][10];
cout << "Enter the size of the matrix:\n";
cin >> n;
cout << "Enter the elements of the matrix:\n";
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
cin >> matrix[i][j];
cout << "The entered matrix is:" << endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
cout << "Determinant of the matrix is " << determinant(matrix, n);
return 0;
}
I know this might be a duplicate to another question on this forum but I couldn't find the solution for my problem, even if I searched for like 1 hour.
The problem is that my program stops after the 4th "cin". I don't know why, I tried everything: "cin.ingore(); cin.clear();", "cin.get();".
Could someone help me please?
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
struct elev
{
char nume[20];
vector<int> note_info;
float medie;
};
int main()
{
int n, e = 0;
vector<elev> elevi;
cout << "n = "; cin >> n;
for (int i = 1; i <= n; i++)
{
int s = 0, nr;
elevi.push_back(elev());
cout << "Nume elev: "; cin >> elevi[i].nume;
cout << "Numar note informatica: "; cin >> nr;
for (int j = 0; j < nr; j++)
{
int temp;
cout << "Nota nr. " << j + 1 << ": "; cin >> temp;
elevi[i].note_info.push_back(temp);
s += temp;
}
elevi[i].medie = (float)(s / nr);
}
for (int i = 1; i <= n; i++)
{
for (int j = i; j <= n; j++)
{
if (elevi[j].medie != elevi[j + 1].medie)
{
e += 1;
}
}
}
if (e)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n - i; j++)
{
if (elevi[j].medie < elevi[j + 1].medie)
{
elev temp = elevi[j];
elevi[j] = elevi[j + 1];
elevi[j + 1] = temp;
}
}
}
}
else
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n - i; j++)
{
if (elevi[j].nume > elevi[j + 1].nume)
{
elev temp = elevi[j];
elevi[j] = elevi[j + 1];
elevi[j + 1] = temp;
}
}
}
}
cout << "Rezultate:";
for (int i = 1; i <= n; i++)
{
cout << '\n' << elevi[i].nume << ' ' << setprecision(2) << fixed << elevi[i].medie;
}
return 0;
}
Replace this line:
for (int i = 1; i <= n; i++)
with
for (int i = 0; i < n; ++i)
The error stems from trying to access the vector elevi at a position it doesn't yet have. Because vectors start indexing at 0, the first access made to elevi should be at index 0.
Recently I engaged in programming. In my school were told to write a program to solve systems of linear equations Gauss method, that's what I did, but I an error "'abs' cannot be used as a function", please tell me how to fix.
#include <iostream>
#include <stdlib.h>
#include <cstdlib>
using namespace std;
// Вывод системы уравнений
void sysout(double **a, double *y, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++){
cout << a[i][j] << "*x" << j;
if (j < n - 1) {
cout << " + ";
}
}
cout << " = " << y[i] << endl;
}
return;
}
double * gauss(double **a, double *y, int n) {
double *x, max;
int k, index;
const double eps = 0.00001; // точность
x = new double[n];
k = 0;
while (k < n) {
// Поиск строки с максимальным a[i][k]
int abs;
max = abs(a[k][k]);
index = k;
for (int i = k + 1; i < n; i++) {
if (abs(a[i][k]) > max) {
max = abs(a[i][k]);
index = i;
}
}
// Перестановка строк
if (max < eps) {
// нет ненулевых диагональных элементов
cout << "Решение получить невозможно из-за нулевого столбца " ;
cout << index << " матрицы A" << endl;
return 0;
}
for (int j = 0; j < n; j++) {
double temp = a[k][j];
a[k][j] = a[index][j];
a[index][j] = temp;
}
double temp = y[k];
y[k] = y[index];
y[index] = temp;
// Нормализация уравнений
for (int i = k; i < n; i++) {
double temp = a[i][k];
if (abs(temp) < eps) continue; // для нулевого коэффициента пропустить
for (int j = 0; j < n; j++) {
a[i][j] = a[i][j] / temp;
}
y[i] = y[i] / temp;
if (i == k) continue; // уравнение не вычитать само из себя
for (int j = 0; j < n; j++) {
a[i][j] = a[i][j] - a[k][j];
}
y[i] = y[i] - y[k];
}
k++;
}
// обратная подстановка
for (k = n - 1; k >= 0; k--) {
x[k] = y[k];
for (int i = 0; i < k; i++) {
y[i] = y[i] - a[i][k] * x[k];
}
}
return x;
}
int main() {
double **a, *y, *x;
int n;
system("chcp 1251>nul");
system("cls");
cout << "Введите количество уравнений: ";
cin >> n;
a = new double*[n];
y = new double[n];
for (int i = 0; i < n; i++) {
a[i] = new double[n];
for (int j = 0; j < n; j++) {
cout << "a[" << i << "][" << j << "]= ";
cin >> a[i][j];
}
}
for (int i = 0; i < n; i++) {
cout << "y[" << i << "]= ";
cin >> y[i];
}
sysout(a, y, n);
x = gauss(a, y, n);
for (int i = 0; i < n; i++){
cout << "x[" << i << "]=" << x[i] << endl;
}
cin.get(); cin.get();
return 0;
}
Change the variable to "fabs" tried to change to "std :: abs" tried. Compiler MiGW.
If you #include <cmath> instead of stdlib.h and cstdlib then it works:
#include <iostream>
#include <cmath>
using namespace std;
// Вывод системы уравнений
void sysout(double **a, double *y, int n) {
...
Also you should remove the int abs; in the while loop.
I'm not sure why #include <cstdlib> should cause problems here - can anyone explain?
Here's an online demo of the code compiling.
Why is the time complexity of this code O(xnm)?
Is this code's time complexity asymptotically tight?
Why?
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
int a[10][10], b[10][10], c[10][10];
int x, y, i, j, m, n;
cout << "\nEnter the number of rows and columns for Matrix A:::\n\n";
cin >> x >> y;
// x denotes number rows in matrix A
// y denotes number columns in matrix A
cout << "\n\nEnter elements for Matrix A :::\n\n";
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
{
cin >> a[i][j];
}
cout << "\n";
}
cout << "\n\nMatrix A :\n\n";
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
{
cout << "\t" << a[i][j];
}
cout << "\n\n";
}
cout << "\n-----------------------------------------------------------\n";
cout << "\nEnter the number of rows and columns for Matrix B:::\n\n";
cin >> m >> n;
// m denotes number rows in matrix B
// n denotes number columns in matrix B
cout << "\n\nEnter elements for Matrix B :::\n\n";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
cin >> b[i][j];
}
cout << "\n";
}
cout << "\n\nMatrix B :\n\n";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
cout << "\t" << b[i][j];
}
cout << "\n\n";
}
if (y == m)
{
for (i = 0; i < x; i++)
{
for (j = 0; j < n; j++)
{
c[i][j] = 0;
for (int k = 0; k < m; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
cout
<< "\n-----------------------------------------------------------\n";
cout << "\n\nMultiplication of Matrix A and Matrix B :\n\n";
for (i = 0; i < x; i++)
{
for (j = 0; j < n; j++)
{
cout << "\t" << c[i][j];
}
cout << "\n\n";
}
}
else
{
cout << "\n\nMultiplication is not possible";
}
getch();
return 0;
}
Because the most computations is done here:
for (i = 0; i < x; i++)
{
for (j = 0; j < n; j++)
{
c[i][j] = 0;
for (int k = 0; k < m; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
The approximation of number of basic operations like addition, multiplication and assignment here is x*n*m. That is why this algorithm has O(x*n*m) asymptotic. But matrix multiplication can be done faster in terms of asymptotic. Just check out related articles about matrix multiplication and big o notation.
Complexity introduction
Faster matrix multiplication approach