/* ex2.cpp
 * Peter Webb, Aug. 1995
 * Example 2 from the documentation: Writing Simple Functions
 */

#include <stdio.h>
#include "matlab.h"

static double data0[] = { 2, 6, 4, 8 };
static double data1[] = { 1, 5, 3, 7 };

Matrix *average(Matrix *m1, Matrix *m2)
{
    /* (m2 + m1) / 2 */
    Matrix *sum, *ave, *two = mlfScalar(2);

    sum = mlfPlus(m1, m2);
    ave = mlfRdivide(sum, two);
    mxFreeMatrix(sum);
    mxFreeMatrix(two);
    return ave;
}

main()
{
    /* Create two matrices */

    Matrix *mat0 = mxCreateFull(2, 2, 0);
    Matrix *mat1 = mxCreateFull(2, 2, 1);
    Matrix *mat2;
 
    memcpy(mxGetPr(mat0), data0, 4 * sizeof(double));
    memcpy(mxGetPr(mat1), data1, 4 * sizeof(double));

    mat2 = average(mat0, mat1);
    mlfPrintMatrix(mat0);
    mlfPrintf(" + \n");
    mlfPrintMatrix(mat1);
    mlfPrintf(" / 2 = \n");
    mlfPrintMatrix(mat2);

    mxFreeMatrix(mat0);
    mxFreeMatrix(mat1);
    mxFreeMatrix(mat2);
    exit(0);
}

