Demo entry 2142776

Projection

   

Submitted by anonymous on Jul 09, 2015 at 11:27
Language: C. Code size: 2.2 kB.

#include <stdio.h>
#include <math.h>

typedef struct Vector {
    int dim;
    double seibun[100];
} Vector;

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

int main() {
    Vector v[3] = {
        {3, {1.0, 0.0, -1.0}},
        {3, {2.0, 1.0, 0.0}},
        {3, {1.0, 2.0, 2.0}},
    };
    printf("ベクトル v0:    \n");
    VecShow(v[0]);
    printf("ベクトル v1:    \n");
    VecShow(v[1]);
    Vector proj = VecProj(v[0],v[1]);
    printf("v0のv1への正射影ベクトル proj: ");
    VecShow(proj);
}

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);
}

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 VecScale(double m, Vector u) {
    Vector tmp;
    tmp.dim=u.dim;
    int i;
    for (i=0; i<tmp.dim; i++)
        tmp.seibun[i] = m*u.seibun[i];
    return tmp;
}

Vector VecAdd(Vector u, Vector v) {
    Vector tmp;
    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 VecSub(Vector u, Vector v) {
    Vector tmp;
    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 VecAdd(Vector u, Vector v) {
    Vector tmp;
    tmp.dim=u.dim;
    int i;
    for (i=0; i<tmp.dim; i++)
        tmp.seibun[i] = u.seibun[i] + v.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));
}

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.02 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).