Question #24605
In the programming language of your choice write a function which uses the Gram-Schmidt process to orthogonalize a 3 by 3 matrix. Use remark statements to explain how the program works. You may want to use your calculator&rsquo;s programming language.
1
2013-02-20T09:05:02-0500
#include <time.h>
#include <conio.h>

#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>

using namespace std;

const int SIZE = 3;

typedef double Matrix[SIZE][SIZE];

double dot_product(double vector_1[SIZE], double vector_2[SIZE])
{
double result = 0;
for (int c = 0; c < SIZE; c++)
result += vector_1[c] * vector_2[c];
return result;
}

void orthogonalize_vector(int n, Matrix &result, Matrix &matrix)
{
double coeff;
for (int j = 0; j < n; j++)
{
coeff = dot_product(matrix[n], result[j]) / dot_product(result[j], result[j]);
for (int k = 0; k < SIZE; k++)
result[n][k] -= result[j][k] * coeff;
}

/* Normalize vector */
double length = 0;
for (int k = 0; k < SIZE; k++)
length += result[n][k] * result[n][k];
length = sqrt(length); //calculate vector length

for (int k = 0; k < SIZE; k++)
result[n][k] /= length;
}

void orthogonalize_matrix(Matrix &matrix)
{
Matrix result;

/* Copy initial matrix to the resulting one */
memcpy(result, matrix, SIZE * SIZE * sizeof(double));

/* Orthogonalize matrix vectors (rows) */
for (int x = 0; x < SIZE; x++)
orthogonalize_vector(x, result, matrix);

/* Copy resulting matrix to the initial one */
memcpy(matrix, result, SIZE * SIZE * sizeof(double));
}

void fill_matrix(Matrix &matrix)
{
for (int x = 0; x < SIZE; x++)
for (int y = 0; y < SIZE; y++)
matrix[x][y] = (rand() % 50) + (rand() % 5);
}

void print_matrix(Matrix &matrix)
{
for (int x = 0; x < SIZE; x++)
{
for (int y = 0; y < SIZE; y++)
cout << setw(8) << setprecision(2) << matrix[x][y];
cout << endl;
}
cout << endl;
}

int main()
{
srand(time(NULL));
Matrix matrix;

fill_matrix(matrix);
cout << "The initial matrix:" << endl;
print_matrix(matrix);

orthogonalize_matrix(matrix);
cout << "The orthogonalized matrix:" << endl;
print_matrix(matrix);

_getch();
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!