MATLAB Answers

Print from C file into Command window via MexFile

28 views (last 30 days)
Hendrik Lorenz
Hendrik Lorenz on 18 Jun 2019
Edited: James Tursa on 18 Jun 2019
I am executing a C function via a mex file in Matlab. I understood that I can output messages from the mex file using mexPrintf as demonstrated in this example:
* mexfunction.c
* This example demonstrates how to use mexFunction. It returns
* the number of elements for each input argument, providing the
* function is called with the same number of output arguments
* as input arguments.
* This is a MEX-file for MATLAB.
* Copyright 1984-2011 The MathWorks, Inc.
* All rights reserved.
#include "mex.h"
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
int i;
/* Examine input (right-hand-side) arguments. */
mexPrintf("\nThere are %d right-hand-side argument(s).", nrhs);
for (i=0; i<nrhs; i++) {
mexPrintf("\n\tInput Arg %i is of type:\t%s ",i,mxGetClassName(prhs[i]));
/* Examine output (left-hand-side) arguments. */
mexPrintf("\n\nThere are %d left-hand-side argument(s).\n", nlhs);
if (nlhs > nrhs)
mexErrMsgIdAndTxt( "MATLAB:mexfunction:inputOutputMismatch",
"Cannot specify more outputs than inputs.\n");
for (i=0; i<nlhs; i++) {
However I would like to print directly from the c-file to Matlab Command Window. Is that possible?
The reason why I want to do that:
I want to raise an error/message if there occur NaN values in my numeric computations within the c-file to determine when and at which point in the code they appear. Since they propagate through the calculations and possibly make the whole function crash it is not enough for me to hand back a NaN-flag variable to the mexFunction after the c-function was executed.
Since this is just for debugging I also don't care about performance. What I would like to avoid though is to start the Visual studio debugger and attach the Matlab process to it as described here (since this is tedious):

  1 Comment

dpb on 18 Jun 2019
So, what's the question? The sample code illustrates both just an informative message plus an error message. The latter also terminates the mex file but if don't want quite so big a club for debugging then mexWarnMsgIdAndTxt won't.
You can output whatever you wish from the context within the function at that point...I forget what NaN control you have within the mex environment to prevent the automagic error exit...

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 18 Jun 2019
Edited: James Tursa on 18 Jun 2019
"However I would like to print directly from the c-file to Matlab Command Window. Is that possible?"
Yes, that is what mexPrintf( ) does, so I am not sure if I understand your problem yet.
If you are searching for NaN values then you may find the mxIsNaN( ) function useful:


Sign in to comment.

More Answers (0)