# Demo entry 2129447

Projection

Submitted by anonymous on Jul 08, 2015 at 11:38
Language: C. Code size: 1.8 kB.

```#include <stdio.h>
#include <math.h>
typedef struct Vector {
int dim;
double seibun[100];
} Vector;

Vector VecScale(double m, Vector u);
double VecDot(Vector u, Vector v);
double VecNorm(Vector u);
Vector VecNormalize(Vector u);
Vector VecProj(Vector u,Vector v);
int VecShow(Vector u);

int main() {
Vector mA[2] = {
{3, {3.0, 5.0, -2.0}},
{3, {4.0, 0.0, 1.0}},
};
printf("ベクトル u:    ");
VecShow(mA[0]);
printf("ベクトル v:    ");
VecShow(mA[1]);
Vector proj = VecProj(mA[0],mA[1]);
printf("ベクトル proj: ");
VecShow(proj);
return 0;
}

Vector VecProj(Vector u,Vector v) {
double dotuv = VecDot(u,v);
double dotvv = VecDot(v,v);
Vector proj  = VecScale(dotuv/dotvv, v);
return proj;
}

Vector VecAdd(Vector u, Vector v) {
Vector tmp = {3,{0.0}};
tmp.dim=u.dim;
int i;
for (i=0; i<tmp.dim; i++)
tmp.seibun[i] = u.seibun[i] + v.seibun[i];
return tmp;
}

Vector VecScale(double m, Vector u) {
Vector tmp = {3,{0.0}};
tmp.dim=u.dim;
int i;
for (i=0; i<tmp.dim; i++)
tmp.seibun[i] = m*u.seibun[i];
return tmp;
}

double VecDot(Vector u, Vector v) {
int i;
double tmp=0.0;
for (i=0; i<u.dim; i++)
tmp += u.seibun[i] * v.seibun[i];
return tmp;
}

double VecNorm(Vector u) {
return sqrt(VecDot(u,u));
}

Vector VecNormalize(Vector u) {
Vector zero = {3,{0.0}};
double norm_u = VecNorm(u);
if (norm_u < 1e-13)
return zero;
else
return VecScale(1/norm_u, u);
}

int VecShow(Vector u) {
int i;
printf("(");
for (i=0; i<u.dim; i++)
printf("%6.2f ",u.seibun[i]);
printf(" )\n");
return 0;
}
```

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.