Listing 3

// Convert RGB values to YUV
// Copyright (C) 2003, Jeff Perry
// jsp created Tue Sep 23 17:10:50 CDT 2003

#include "mex.h"
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Check inputs
    if (nrhs != 1)
        mexErrMsgTxt ("This function requires 1 input.");
    // Check outputs
    if (nlhs > 1)
        mexErrMsgTxt ("Too many return values were specified.");
    // Check input types
    if (!mxIsDouble (prhs[0]) || mxIsComplex (prhs[0]))
        mexErrMsgTxt ("The input must be a noncomplex double.\n");
    // Get input dimensions
    int ndims = mxGetNumberOfDimensions (prhs[0]);
    const int *dims = mxGetDimensions (prhs[0]);
    if ((ndims != 2 && ndims != 3) || dims[ndims-1] != 3)
        mexErrMsgTxt ("The input must be either N X 3 or M X N X 3");
    // Allocate the outputs
    plhs[0] = mxCreateNumericArray (ndims, dims, mxDOUBLE_CLASS, mxREAL);
    // Get pointers to inputs and outputs
    double *yuv = mxGetPr (plhs[0]);
    double *rgb = mxGetPr (prhs[0]);
    // Determine how many iterations we need
    int total = mxGetNumberOfElements (prhs[0]) / 3;
    // Do the conversion
    for (int n = 0; n < total; ++n)
    {
        yuv[n+0*total] =  
                0.2122*rgb[n] + 0.7013*rgb[n+total] + 0.0865*rgb[n+2*total];
        yuv[n+1*total] = 
               -0.1162*rgb[n] - 0.3838*rgb[n+total] + 0.5000*rgb[n+2*total];
        yuv[n+2*total] =  
                0.5000*rgb[n] - 0.4451*rgb[n+total] - 0.0549*rgb[n+2*total];
    }
}