Reputation: 101
I want to "append" a vector to matrix, eg
[1 2; & (5 [1 2 5;
3 4] 6) --> 3 4 6];
trying to emulate math script. I seemingly don't understand arrays and pointers in C because when I try to do that in C I with the following code
EDIT: Posted messed up code which was redundant. When using the function mmerge, the "problem" persists.
#include <stdio.h>
//void printMatrix(const int N, const int M, double A[N][M]);
void mmerge(const int N, const double A[N][N], const double b[N], double F[N][N])
{
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
F[i][j] = A[i][j];
}
F[i][N] = b[i];
}
}
// Prints a two-dimensional array as a matrix
void printMatrix(const int N, const int M, double A[N][M]){
int i, j;
for(i=0; i<N; ++i){
printf("|");
for(j=0; j<M; ++j){
printf(" % 8.4f", A[i][j]);
if(j != M-1) printf(",");
}
printf(" |\n");
}
printf("\n");
}
int main()
{
const int N=2;
double A[2][2] = {{1,2},{3,4}};
double b[2] = {5,6};
double F[2][3];
mmerge(2,A,b,F);
printMatrix(2, 3, F);
return 0;
}
I get
| 1.0000, 2.0000, 3.0000 |
| 4.0000, 6.0000, 0.0000 |
What happens and why is it not the expected result?
Upvotes: 0
Views: 1014
Reputation: 926
/Bro your code is wrong here/
void mmerge(const int N, const double A[N][N], const double b[N], double F[N][N]+1)
use double F[N][N+1]) instead of double F[N][N]+1).
Corrected code with correct output
Upvotes: 0
Reputation: 101
Forgot N+1
I want to "append" a vector to matrix, eg
[1 2; & (5 [1 2 5;
3 4] 6) --> 3 4 6];
trying to emulate math script. I seemingly don't understand arrays and pointers in C because when I try to do that in C I with the following code
EDIT: Posted messed up code which was redundant. When using the function mmerge, the "problem" persists.
#include <stdio.h>
//void printMatrix(const int N, const int M, double A[N][M]);
void mmerge(const int N, const double A[N][N], const double b[N], double F[N][N]+1)
{
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
F[i][j] = A[i][j];
}
F[i][N] = b[i];
}
}
// Prints a two-dimensional array as a matrix
void printMatrix(const int N, const int M, double A[N][M]){
int i, j;
for(i=0; i<N; ++i){
printf("|");
for(j=0; j<M; ++j){
printf(" % 8.4f", A[i][j]);
if(j != M-1) printf(",");
}
printf(" |\n");
}
printf("\n");
}
int main()
{
const int N=2;
double A[2][2] = {{1,2},{3,4}};
double b[2] = {5,6};
double F[2][3];
mmerge(2,A,b,F);
printMatrix(2, 3, F);
return 0;
}
Upvotes: 1
Reputation: 547
What does your function after double F[2][3]; do?
Also, your merging function should be like this
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
F[i][j] = A[i][j];
}
}
for(j = 0; j < N; j++) {
F[j][M-1] = b[j];
}
Upvotes: 0