I'm writing a program that multiplies a vector by a constant matrix, and then adds a constant vector to that result. The vector is then normalized, and the process continues.
Unfortunately, my program runs but I'm not seeing the correct results. Here's the code:
#include <stdio.h>
#include <math.h>
double unit_norm(double x[4], int cols);
void matrix_mult(double K[4][4], double x[4], double y[4], int rows);
main()
{
int rows = 4, cols = 4, k, rep = 0;
double K[4][4] = { { 2., -4., 0., 1.},
{-4., 5., -2., 1.},
{ 1., -1., 6., -3.},
{ 0., 2., -3., 7.}};
double x[4] = { 1./3, 2./3, -1./3, pow(3.,0.5)/3.};
double a[4] = { 1./4., -1./2, 3./4, sqrt(2.)/.4};
double y[4] = { 0, 0, 0, 0};
printf("\nInitial vector:\n");
printf("x[%d] = [ ", rep);
for (k=0; k<rows; k++) printf("%f ",x[k]);
printf("]\n\n");
for (rep=1; rep<8; rep++)
{
matrix_mult(K, x, y, rows);
for (k=0; k<rows; k++) x[k]=a[k]+y[k];
k=0;
for (k=0; k<rows; k++) y[k]=0;
k=0;
printf("New vector:\n");
printf("x[%d] = [ ", rep);
for (k=0; k<rows; k++) printf("%f ",x[k]);
k=0;
printf("]\n");
printf("The length of this vector is %f\n", unit_norm(x, cols));
printf("Normalized new vector:\n");
printf("x[%d] = [ ", rep);
for (k=0; k<rows; k++) printf("%f ",x[k]);
printf("]\n\n");
}
}
void matrix_mult(double K[4][4], double x[4], double y[4], int rows)
{
int j, i;
double dot_p;
for(i=0; i<rows; i++);
{
for(j=0, dot_p=0.; j<rows; j++)
{
dot_p += K[i][j] * x[j];
}
y[i] = dot_p;
}
return;
}
double unit_norm(double x[4], int cols)
{
double sum=0;
int i;
for (i=0; i<4; i++) sum += x[i] * x[i];
sum = sqrt(sum);
for(i=0; i<4; i++) x[i]=x[i]/sum;
return sum;
}
Results I should be getting:
Initial vector: x[0] = [ 0.333333 0.666667 -0.333333 0.577350] New vector: x[1] = [-1.172650 2.744017 -3.315384 9.910319] The length of this vector is: 10.867885 Normalized new vector: x[1] = [-0.107900 0.252489 -0.305062 0.911890] New vector: x[2] = [-0.063865 2.716060 -4.176435 11.338931] The length of this vector is: 12.385274 Normalized new vector: x[2] = [-0.005157 0.219298 -0.337210 0.915517]
.... and so on until x[7] . Any ideas where I went wrong?
Thanks,
Rogan


Sign In
Create Account

Back to top









