This is what my program is supposed to do:
- Print the vector (m1)
- Print the matrix (m2)
- Multiply the vector and matrix together and display results
The only thing wrong with my program is that I can't quite get the right results displayed.
The correct display of values should be:
30
70
110
150
My Values displayed are:
30
71
115
159
The display of the first number (A[0][0]) is correct (30). But A[1][0] is off by 1; A[2][0] is off by 5; A[3][0] is off by 9.
I noticed that x[0][0] is 1; x[0][1] is 5; and x[0][2] is 9. But I still cannot figure out why this is off.
If you change line 78 from '+=' to '=', it will print out a chart of the values without adding them together. Then if you add the columns displayed you get the right sums, but once you change it back to '+=' it becomes off by the numbers I stated above.
I have tried changing some of the values in m1 to see if the same pattern persists, and the pattern does persist. If you have any ideas or know figure out what's wrong, it would be much appreciated.
/*
Filename: prog_5.c
Creator: Spencer Beale
Date: 11/8/10
About: This program will multiply a matrix by a vector and display the results, vector, and matrix.
*/
#include <stdio.h>
int main()
{
// Define Variables
int n = 4;
int m1[4] = {1, 2, 3, 4};
int m2[4][4] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
int multiplied_matrix[4][1] = {
{0},
{0},
{0},
{0}
};
// Define Functions
void print_matrix(int n, int m[n][n]); // Prints an nxn matrix
void print_vector(int n, int v[n]); // Prints a vector of n elements
void matrix_x_vector(int n, int y[n], int x[n][n], int A[n][n]); // Performs the calculation
// Execute Functions
print_vector(n, m1);
print_matrix(n, m2);
matrix_x_vector(n, m1, m2, multiplied_matrix);
printf("\n");
}
void print_matrix(int n, int m[n][n])
{
int i, j; // i = row; j = column;
printf("\nMatrix Given\n");
for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
printf("%3i", m[i][j]);
printf("\n");
}
}
void print_vector(int n, int v[n])
{
int i;
printf("\nVector Given\n");
for (i=0; i<n; i++)
printf("%3i", v[i]);
printf("\n");
}
void matrix_x_vector(int n, int y[n], int x[n][n], int A[n][n])
{
int i, j; // i = row; j = column;
printf("\nResulted Matrix of [M]*[V]\n");
// Load up A[n][n]
for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
{
A[j][0] += x[j][i] * y[i];
printf("%4i", A[j][0]);
}
printf("\n");
}
printf("\n");
// Print A[n][n]
for (i=0; i<n; i++)
printf("%4i\n", A[i][0]);
}
(The document of code is included to downloaded and mess with if you so desire to do so.)