![](/img/trans.png)
[英]How can I seed and call C++ random number generator from MATLAB mex function?
[英]how can I make a mex function printf while it's running?
我有一個在我的MATLAB腳本中調用的mex文件。 mex函數可能需要一段時間才能運行,因此為了防止我的代碼“在沒有任何輸出的情況下停在那里”,我在mex文件中放入了許多printf
語句來輸出有關正在處理的數據的一些運行信息。
但是當我調用mex函數時,它不會printf
任何東西並在int運行期間保持不變。 最后,在完成其工作后,它將printf
出我想要的所有信息 - 不是在運行時,而是在完成之后 。 這不是我想要的。
所以我想知道如何不僅使printf
成為我想要的東西,而且在我想要的時候也知道printf
。
是的, mexPrintf
就是您所需要的。 但請注意,命令窗口不會強制刷新它使用的緩沖區,通常會在打印消息之前導致很長的延遲。 如果在調用mexPrintf
后開始繁重的計算,就會發生這種情況。
解決方法是使用
mexEvalString("drawnow;")
每次打電話給mexPrintf
。
如果您發現沒有吸引力,可以創建一個調用兩者的宏:
#define printfFnc(...) { mexPrintf(__VA_ARGS__); mexEvalString("drawnow;");}
這使用了可變參數宏__VA_ARGS__
。 它可能不是標准的一部分,但似乎是在GCC和Visual C ++中。 只需調用printfFnc
就像調用printf
(或mexPrintf
)一樣。
有一個未記錄的C ++函數駐留在libmwservices.dll
。 它顯然會刷新輸出緩沖區。 這是一個例子:
#include "mex.h"
#pragma comment(lib, "libmwservices.lib")
extern bool ioFlush(void);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
for(int i=0; i<100000; i++) {
mexPrintf("%d\n", i);
ioFlush();
}
}
只需將其編譯為: mex -largeArrayDims test_mex_print.cpp
你可以使用mexPrintf
*
* mex equivalent to MATLAB's "disp" function
*/
extern int mexPrintf(const char *fmt, /* printf style format */
... /* any additional arguments */);
我有與OP相同的問題,其中mexPrintf()在mex文件完成運行之前不會打印任何輸出。 而且,mexEvalString(“drawnow;”); 似乎沒有解決問題,或者至少它沒有我的設置(MATLAB2015b與C ++ 11 MEX代碼的64位MinGW編譯器)。
但是,使用mexEvalString(“pause(.001);”); 在mexPrintf()確實修復它之后。 我花了一些試錯才弄清楚,所以我希望這可能對將來的參考有用。
TLDR:使用mexEvalString(“pause(.001);”);
printf打印到stdout,這不是 matlab屏幕。 (默認隱藏,最后收集/顯示)
試試mexprintf():
http://www.mathworks.co.uk/help/matlab/apiref/mexprintf.html
在C MEX文件中,您必須調用mexPrintf而不是printf來顯示字符串。
C Syntax
#include "mex.h"
int mexPrintf(const char *message, ...);
Arguments
message
String to display. In C, the string can include conversion specifications, used by the ANSI® C printf function.
...
In C, any arguments used in the message. Each argument must have a corresponding conversion specification.
Returns
Number of characters printed including characters specified with backslash codes, such as \n and \b.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.